import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { 
  Brain, 
  Sword, 
  Bot, 
  Zap, 
  Crown, 
  Flame, 
  Star, 
  Sparkles, 
  Gamepad2, 
  ArrowLeft, 
  Trophy, 
  Timer,
  Target,
  Shield,
  Rocket,

  ChevronRight,
  Play,
  Pause,
  RotateCcw,
  Check,
  X,
  Circle,
  Square,
  Triangle,
  MousePointer,
  Users,
  Medal,
  TrendingUp,
  Calendar,
  Gift,
  Swords,
  UserCheck,
  Plus,
  UserPlus,
  MessageCircle,
  Eye,
  Search,
  Settings,
  Lock,
  Globe,
  Wifi,
  WifiOff,
  Clock,
  Send,
  Mic,
  MicOff,
  Volume2,
  VolumeX,
  UserX,
  Heart,
  Share2,
  Copy,
  MoreHorizontal
} from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult, TestType } from '../types';
import { 
  AIBattleResult, 
  PlayerRank, 
  BattleTeam, 
  TeamBattleStats, 
  TeamBattleChallenge,
  PvPPlayer,
  BattleRoom,
  RoomSettings,
  MatchmakingQueue,
  ChatMessage,
  Friend,
  PvPBattleStats
} from '../types/aiBattle';
import { tests } from '../constants/tests';

interface AIOpponent {
  id: string;
  name: string;
  emoji: string;
  level: number;
  description: string;
  personality: string;
  difficulty: number;
  specialties: string[];
  color: string;
  bgGradient: string;
}

interface BattleStats {
  playerScore: number;
  aiScore: number;
  round: number;
  totalRounds: number;
  timeRemaining: number;
  playerCorrect: number;
  aiCorrect: number;
}

interface Challenge {
  id: number;
  type: 'reaction' | 'memory' | 'math' | 'pattern' | 'color' | 'logic' | 'word' | 'sequence' | 'spatial' | 'attention' | 'comparison' | 'calculation';
  category: string;
  difficulty: 'easy' | 'medium' | 'hard';
  question: string;
  options?: string[];
  correctAnswer: string | number;
  playerAnswer?: string | number;
  aiAnswer?: string | number;
  timeToAnswer?: number;
  completed: boolean;
}

interface AIBattleModeProps {
  onComplete: (result: TestResult) => void;
  onBack: () => void;
}

const aiOpponents: AIOpponent[] = [
  {
    id: 'rookie',
    name: 'R.O.O.K.I.E',
    emoji: '🤖',
    level: 1,
    description: '友好的新手AI',
    personality: '友善、鼓励性，反应较慢',
    difficulty: 0.6,
    specialties: ['基础反应', '简单逻辑'],
    color: 'text-green-600',
    bgGradient: 'from-green-50 to-emerald-50'
  },
  {
    id: 'strategist',
    name: '策略大师',
    emoji: '🧠',
    level: 2,
    description: '专精逻辑思维',
    personality: '冷静、分析性，擅长复杂推理',
    difficulty: 0.75,
    specialties: ['逻辑推理', '策略规划', '模式识别'],
    color: 'text-blue-600',
    bgGradient: 'from-blue-50 to-indigo-50'
  },
  {
    id: 'speedster',
    name: '闪电侠',
    emoji: '⚡',
    level: 3,
    description: '极速反应专家',
    personality: '快速、激进，反应速度惊人',
    difficulty: 0.85,
    specialties: ['反应速度', '快速决策', '动作协调'],
    color: 'text-yellow-600',
    bgGradient: 'from-yellow-50 to-orange-50'
  },
  {
    id: 'mastermind',
    name: '终极智脑',
    emoji: '👑',
    level: 4,
    description: '全能型超级AI',
    personality: '完美主义、极具挑战性，几乎无懈可击',
    difficulty: 0.95,
    specialties: ['全能力测试', '适应性学习', '完美执行'],
    color: 'text-purple-600',
    bgGradient: 'from-purple-50 to-pink-50'
  }
];

// 模拟在线玩家数据
const mockOnlinePlayers: PvPPlayer[] = [
  {
    id: '1',
    name: '战神小明',
    avatar: '🦅',
    level: 45,
    rank: 1,
    rankPoints: 2850,
    winRate: 75,
    isOnline: true,
    status: 'idle',
    currentStreak: 8,
    title: '至尊王者',
    badge: '👑'
  },
  {
    id: '2',
    name: 'AI克星',
    avatar: '⚡',
    level: 42,
    rank: 2,
    rankPoints: 2720,
    winRate: 69,
    isOnline: true,
    status: 'searching',
    currentStreak: 5,
    title: '星耀大师',
    badge: '⭐'
  },
  {
    id: '3',
    name: '反应王',
    avatar: '🔥',
    level: 38,
    rank: 3,
    rankPoints: 2580,
    winRate: 65,
    isOnline: true,
    status: 'in-game',
    currentStreak: 3,
    title: '钻石精英',
    badge: '💎'
  },
  {
    id: '4',
    name: '速算达人',
    avatar: '🧮',
    level: 35,
    rank: 8,
    rankPoints: 2200,
    winRate: 72,
    isOnline: true,
    status: 'idle',
    currentStreak: 12,
    title: '铂金高手',
    badge: '🥈'
  },
  {
    id: '5',
    name: '记忆大师',
    avatar: '🧠',
    level: 33,
    rank: 12,
    rankPoints: 1980,
    winRate: 68,
    isOnline: true,
    status: 'spectating',
    currentStreak: 4,
    title: '黄金勇士',
    badge: '🥉'
  }
];

// 模拟房间数据
const mockBattleRooms: BattleRoom[] = [
  {
    id: 'room1',
    name: '王者争霸赛',
    mode: 'ranked',
    maxPlayers: 2,
    currentPlayers: 1,
    players: [mockOnlinePlayers[0]],
    spectators: [],
    status: 'waiting',
    settings: {
      rounds: 5,
      timePerRound: 15,
      difficulty: 'hard',
      categories: ['全部'],
      allowSpectators: true,
      maxSpectators: 10,
      chatEnabled: true,
      voiceChatEnabled: false
    },
    createdBy: '1',
    createdAt: new Date(),
    isPrivate: false
  },
  {
    id: 'room2',
    name: '新手友谊赛',
    mode: 'casual',
    maxPlayers: 2,
    currentPlayers: 2,
    players: [mockOnlinePlayers[3], mockOnlinePlayers[4]],
    spectators: [mockOnlinePlayers[1]],
    status: 'in-progress',
    settings: {
      rounds: 3,
      timePerRound: 20,
      difficulty: 'easy',
      categories: ['反应', '记忆'],
      allowSpectators: true,
      maxSpectators: 5,
      chatEnabled: true,
      voiceChatEnabled: true
    },
    createdBy: '4',
    createdAt: new Date(Date.now() - 300000),
    isPrivate: false
  },
  {
    id: 'room3',
    name: '私人训练室',
    mode: 'private',
    maxPlayers: 2,
    currentPlayers: 1,
    players: [mockOnlinePlayers[2]],
    spectators: [],
    status: 'waiting',
    settings: {
      rounds: 7,
      timePerRound: 12,
      difficulty: 'mixed',
      categories: ['全部'],
      allowSpectators: false,
      maxSpectators: 0,
      chatEnabled: false,
      voiceChatEnabled: false
    },
    createdBy: '3',
    createdAt: new Date(Date.now() - 120000),
    isPrivate: true,
    password: '123456'
  }
];

// 模拟好友数据
const mockFriends: Friend[] = [
  {
    id: 'f1',
    name: '逻辑大神',
    avatar: '🎯',
    level: 40,
    isOnline: true,
    status: '正在对战中...',
    addedDate: new Date(2024, 6, 15),
    mutualFriends: 3
  },
  {
    id: 'f2',
    name: '反应怪物',
    avatar: '⚡',
    level: 36,
    isOnline: true,
    status: '寻找对手...',
    addedDate: new Date(2024, 7, 2),
    mutualFriends: 1
  },
  {
    id: 'f3',
    name: '记忆达人',
    avatar: '🧭',
    level: 28,
    isOnline: false,
    status: '离线',
    addedDate: new Date(2024, 5, 20),
    lastSeen: new Date(2024, 7, 30),
    mutualFriends: 5
  }
];

// 模拟排行榜数据
const mockLeaderboard: PlayerRank[] = [
  {
    playerId: '1',
    playerName: '战神小明',
    rank: 1,
    rankPoints: 2850,
    wins: 45,
    losses: 12,
    draws: 3,
    winRate: 75,
    totalBattles: 60,
    currentStreak: 8,
    bestStreak: 15,
    averageScore: 87,
    season: 'S1',
    title: '至尊王者',
    badge: '👑'
  },
  {
    playerId: '2',
    playerName: 'AI克星',
    rank: 2,
    rankPoints: 2720,
    wins: 38,
    losses: 15,
    draws: 2,
    winRate: 69,
    totalBattles: 55,
    currentStreak: 5,
    bestStreak: 12,
    averageScore: 84,
    season: 'S1',
    title: '星耀大师',
    badge: '⭐'
  },
  {
    playerId: '3',
    playerName: '反应王',
    rank: 3,
    rankPoints: 2580,
    wins: 42,
    losses: 18,
    draws: 5,
    winRate: 65,
    totalBattles: 65,
    currentStreak: 3,
    bestStreak: 10,
    averageScore: 81,
    season: 'S1',
    title: '钻石精英',
    badge: '💎'
  }
];

export function AIBattleMode({ onComplete, onBack }: AIBattleModeProps) {
  const [activeTab, setActiveTab] = useState<'solo' | 'team' | 'pvp' | 'leaderboard'>('solo');
  const [phase, setPhase] = useState<'selection' | 'preparation' | 'battle' | 'result'>('selection');
  const [preparationCountdown, setPreparationCountdown] = useState(5);
  const [preparationStartTime, setPreparationStartTime] = useState<number | null>(null);
  const [selectedAI, setSelectedAI] = useState<AIOpponent | null>(null);
  const [battleMode, setBattleMode] = useState<'solo' | 'team'>('solo');
  const [battleStats, setBattleStats] = useState<BattleStats>({
    playerScore: 0,
    aiScore: 0,
    round: 1,
    totalRounds: 5,
    timeRemaining: 15,
    playerCorrect: 0,
    aiCorrect: 0
  });
  const [teamBattleStats, setTeamBattleStats] = useState<TeamBattleStats>({
    playerTeamScore: 0,
    aiTeamScore: 0,
    round: 1,
    totalRounds: 6,
    timeRemaining: 20,
    playerTeamCorrect: 0,
    aiTeamCorrect: 0,
    currentPlayerIndex: 0,
    completedChallenges: []
  });
  const [currentChallenge, setCurrentChallenge] = useState<Challenge | null>(null);
  const [battleStarted, setBattleStarted] = useState(false);
  const [battleResult, setBattleResult] = useState<'victory' | 'defeat' | 'draw' | null>(null);
  const [finalTestResult, setFinalTestResult] = useState<TestResult | null>(null);
  const [showPlayerAnswer, setShowPlayerAnswer] = useState(false);
  const [showAIAnswer, setShowAIAnswer] = useState(false);
  
  // AI状态追踪
  const [aiStatus, setAiStatus] = useState<'waiting' | 'thinking' | 'answering' | 'completed'>('waiting');
  const [aiThinkingProgress, setAiThinkingProgress] = useState(0);
  const [aiAnswerTime, setAiAnswerTime] = useState<number | null>(null);
  
  const [playerTeam, setPlayerTeam] = useState<string[]>(['你', 'AI队友1', 'AI队友2']);
  const [selectedTeamSize, setSelectedTeamSize] = useState<2 | 3>(3);
  
  // PvP相关状态
  const [pvpMode, setPvpMode] = useState<'matchmaking' | 'rooms' | 'friends' | 'battle'>('matchmaking');
  const [isSearching, setIsSearching] = useState(false);
  const [searchTime, setSearchTime] = useState(0);
  const [matchFound, setMatchFound] = useState(false);
  const [currentRoom, setCurrentRoom] = useState<BattleRoom | null>(null);
  const [opponent, setOpponent] = useState<PvPPlayer | null>(null);
  const [pvpBattleStats, setPvpBattleStats] = useState<PvPBattleStats>({
    player1Score: 0,
    player2Score: 0,
    player1Correct: 0,
    player2Correct: 0,
    round: 1,
    totalRounds: 5,
    timeRemaining: 15,
    currentQuestion: 1
  });
  const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [showCreateRoom, setShowCreateRoom] = useState(false);
  const [roomSettings, setRoomSettings] = useState<RoomSettings>({
    rounds: 5,
    timePerRound: 15,
    difficulty: 'medium',
    categories: ['全部'],
    allowSpectators: true,
    maxSpectators: 10,
    chatEnabled: true,
    voiceChatEnabled: false
  });
  
  // 匹配设置状态
  const [matchSettings, setMatchSettings] = useState({
    mode: 'ranked' as 'ranked' | 'casual',
    difficulty: 'medium' as 'easy' | 'medium' | 'hard' | 'mixed',
    region: 'auto' as 'auto' | 'asia' | 'america' | 'europe',
    maxWaitTime: 60
  });
  
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const [reactionStartTime, setReactionStartTime] = useState<number | null>(null);
  const [challengeStartTime, setChallengeStartTime] = useState<number | null>(null);

  // 扩展的挑战题库 - 支持12种题目类型和多种难度
  const generateChallenge = (round: number, isTeamMode: boolean = false): Challenge => {
    const challengeTypes: Challenge['type'][] = [
      'reaction', 'memory', 'math', 'pattern', 'color', 'logic', 
      'word', 'sequence', 'spatial', 'attention', 'comparison', 'calculation'
    ];
    
    // 根据AI对手的专长调整题目类型权重
    let weightedTypes = [...challengeTypes];
    if (selectedAI) {
      if (selectedAI.specialties.includes('逻辑推理')) {
        weightedTypes.push('logic', 'sequence');
      }
      if (selectedAI.specialties.includes('快速决策')) {
        weightedTypes.push('reaction', 'attention');
      }
      if (selectedAI.specialties.includes('模式识别')) {
        weightedTypes.push('pattern', 'spatial');
      }
    }
    
    const type = weightedTypes[Math.floor(Math.random() * weightedTypes.length)];
    const baseDifficulty = isTeamMode ? 'medium' : 'easy';
    const difficulty = Math.random() > 0.3 ? baseDifficulty : 'hard';
    
    switch (type) {
      case 'reaction':
        const reactionVariants = [
          '当看到绿色圆圈时点击！',
          '看到蓝色方块立即点击！',
          '红色信号出现时快速点击！',
          '当图标闪烁时点击按钮！'
        ];
        return {
          id: round,
          type: 'reaction',
          category: '反应速度',
          difficulty,
          question: isTeamMode ? '团队反应测试：看到信号立即点击！' : 
                   reactionVariants[Math.floor(Math.random() * reactionVariants.length)],
          correctAnswer: 'click',
          completed: false
        };
      
      case 'memory':
        const length = difficulty === 'easy' ? (isTeamMode ? 4 : 3) : 
                      difficulty === 'medium' ? (isTeamMode ? 5 : 4) : (isTeamMode ? 6 : 5);
        const memoryTypes = [
          () => {
            // 数字记忆 - 选择单个正确数字
            const sequence = Array.from({ length }, () => Math.floor(Math.random() * 9) + 1);
            const correctIndex = Math.floor(Math.random() * sequence.length);
            const correctItem = sequence[correctIndex];
            // 创建包含正确答案的选项，并添加其他数字作为干扰项
            const distractors = Array.from({ length: 3 }, () => {
              let num;
              do {
                num = Math.floor(Math.random() * 9) + 1;
              } while (sequence.includes(num));
              return num;
            });
            const allOptions = [...new Set([correctItem, ...distractors])].map(String).slice(0, 4);
            return {
              question: `记住数字序列：${sequence.join(' - ')}，第${correctIndex + 1}个数字是？`,
              options: allOptions,
              correctAnswer: correctItem.toString()
            };
          },
          () => {
            // 颜色记忆 - 选择单个正确颜色
            const colors = ['红', '蓝', '绿', '黄', '紫', '橙'];
            const sequence = Array.from({ length: Math.min(length, 4) }, () => colors[Math.floor(Math.random() * colors.length)]);
            const correctIndex = Math.floor(Math.random() * sequence.length);
            const correctItem = sequence[correctIndex];
            // 创建选项，包含序列中出现的颜色和一些干扰项
            const distractors = colors.filter(color => !sequence.includes(color)).slice(0, 2);
            const allOptions = [...new Set([correctItem, ...sequence.slice(0, 2), ...distractors])].slice(0, 4);
            return {
              question: `记住颜色序列：${sequence.join(' → ')}，第${correctIndex + 1}个颜色是？`,
              options: allOptions,
              correctAnswer: correctItem
            };
          },
          () => {
            // 字母记忆 - 选择单个正确字母
            const letters = ['A', 'B', 'C', 'D', 'E', 'F'];
            const sequence = Array.from({ length: Math.min(length, 4) }, () => letters[Math.floor(Math.random() * letters.length)]);
            const correctIndex = Math.floor(Math.random() * sequence.length);
            const correctItem = sequence[correctIndex];
            // 创建选项
            const distractors = letters.filter(letter => !sequence.includes(letter)).slice(0, 2);
            const allOptions = [...new Set([correctItem, ...sequence.slice(0, 2), ...distractors])].slice(0, 4);
            return {
              question: `记住字母序列：${sequence.join(' - ')}，第${correctIndex + 1}个字母是？`,
              options: allOptions,
              correctAnswer: correctItem
            };
          }
        ];
        const memoryChallenge = memoryTypes[Math.floor(Math.random() * memoryTypes.length)]();
        return {
          id: round,
          type: 'memory',
          category: '记忆测试',
          difficulty,
          question: memoryChallenge.question,
          options: memoryChallenge.options,
          correctAnswer: memoryChallenge.correctAnswer,
          completed: false
        };
        
      case 'math':
        const mathTypes = [
          () => {
            const a = Math.floor(Math.random() * (difficulty === 'hard' ? 100 : 50)) + 5;
            const b = Math.floor(Math.random() * (difficulty === 'hard' ? 50 : 30)) + 5;
            const op = ['+', '-'][Math.floor(Math.random() * 2)];
            const result = op === '+' ? a + b : a - b;
            // 生成干扰选项
            const wrongOptions = [
              result + Math.floor(Math.random() * 10) + 1,
              result - Math.floor(Math.random() * 10) - 1,
              result + Math.floor(Math.random() * 5) + 5
            ].filter(n => n > 0 && n !== result);
            const allOptions = [result, ...wrongOptions.slice(0, 3)].sort(() => Math.random() - 0.5);
            return { 
              question: `${a} ${op} ${b} = ?`, 
              answer: result.toString(), 
              options: allOptions.map(String) 
            };
          },
          () => {
            const a = Math.floor(Math.random() * 12) + 2;
            const b = Math.floor(Math.random() * (difficulty === 'hard' ? 12 : 8)) + 2;
            const result = a * b;
            // 生成干扰选项
            const wrongOptions = [
              result + a, // 常见错误：加法而不是乘法
              result - b, // 常见错误：减法
              (a + 1) * b, // 常见错误：a+1
              a * (b + 1) // 常见错误：b+1
            ].filter(n => n > 0 && n !== result);
            const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
            const allOptions = [result, ...uniqueWrongOptions].sort(() => Math.random() - 0.5);
            return { 
              question: `${a} × ${b} = ?`, 
              answer: result.toString(), 
              options: allOptions.map(String) 
            };
          },
          () => {
            const nums = Array.from({ length: 3 }, () => Math.floor(Math.random() * 20) + 1);
            const result = nums.reduce((sum, num) => sum + num, 0);
            // 生成干扰选项
            const wrongOptions = [
              result + Math.floor(Math.random() * 5) + 1,
              result - Math.floor(Math.random() * 5) - 1,
              result + nums[0], // 常见错误：重复加第一个数
              result - nums[2] // 常见错误：减最后一个数
            ].filter(n => n > 0 && n !== result);
            const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
            const allOptions = [result, ...uniqueWrongOptions].sort(() => Math.random() - 0.5);
            return { 
              question: `${nums.join(' + ')} = ?`, 
              answer: result.toString(), 
              options: allOptions.map(String) 
            };
          },
          () => {
            const base = Math.floor(Math.random() * 8) + 2;
            const exp = difficulty === 'hard' ? Math.floor(Math.random() * 3) + 3 : 2;
            const result = Math.pow(base, exp);
            // 生成干扰选项
            const wrongOptions = [
              base * exp, // 常见错误：乘法而不是乘方
              Math.pow(base, exp - 1), // 指数减1
              Math.pow(base - 1, exp), // 底数减1
              result + base // 加上底数
            ].filter(n => n > 0 && n !== result);
            const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
            const allOptions = [result, ...uniqueWrongOptions].sort(() => Math.random() - 0.5);
            return { 
              question: `${base}^${exp} = ?`, 
              answer: result.toString(), 
              options: allOptions.map(String) 
            };
          }
        ];
        const mathChallenge = mathTypes[Math.floor(Math.random() * mathTypes.length)]();
        return {
          id: round,
          type: 'math',
          category: '数学计算',
          difficulty,
          question: mathChallenge.question,
          options: mathChallenge.options,
          correctAnswer: mathChallenge.answer,
          completed: false
        };
        
      case 'pattern':
        const patternTypes = [
          () => {
            const symbols = ['🔴', '🔵', '🟢', '🟡', '⭐', '🌙'];
            const patternLength = difficulty === 'hard' ? 5 : 4;
            // 创建简单的交替模式
            const pattern = Array.from({ length: patternLength }, (_, i) => symbols[i % 2]);
            const nextSymbol = symbols[patternLength % 2]; // 下一个应该是什么
            // 创建包含正确答案的选项
            const wrongOptions = symbols.filter(s => s !== nextSymbol).slice(0, 3);
            const allOptions = [nextSymbol, ...wrongOptions].sort(() => Math.random() - 0.5);
            return {
              question: `找规律：${pattern.join(' ')} ?`,
              options: allOptions,
              answer: nextSymbol
            };
          },
          () => {
            const sequences = [
              { nums: [2, 4, 6, 8], next: 10, rule: '+2' },
              { nums: [1, 3, 5, 7], next: 9, rule: '+2' },
              { nums: [2, 4, 8, 16], next: 32, rule: '×2' },
              { nums: [1, 2, 4, 8], next: 16, rule: '×2' },
              { nums: [10, 8, 6, 4], next: 2, rule: '-2' },
              { nums: [20, 16, 12, 8], next: 4, rule: '-4' }
            ];
            const selected = sequences[Math.floor(Math.random() * sequences.length)];
            const wrongOptions = [selected.next + 1, selected.next - 1, selected.next + 2]
              .filter(n => n !== selected.next && n > 0);
            const allOptions = [selected.next, ...wrongOptions.slice(0, 3)].sort(() => Math.random() - 0.5);
            return {
              question: `数列规律：${selected.nums.join(', ')} ?`,
              options: allOptions.map(String),
              answer: selected.next.toString()
            };
          }
        ];
        const patternChallenge = patternTypes[Math.floor(Math.random() * patternTypes.length)]();
        return {
          id: round,
          type: 'pattern',
          category: '模式识别',
          difficulty,
          question: patternChallenge.question,
          options: patternChallenge.options,
          correctAnswer: patternChallenge.answer,
          completed: false
        };
        
      case 'color':
        const colorChallenges = [
          () => {
            const colors = ['红色', '蓝色', '绿色', '黄色', '紫色', '橙色'];
            const colorEmojis = ['🔴', '🔵', '🟢', '🟡', '🟣', '🟠'];
            const index = Math.floor(Math.random() * colors.length);
            const numOptions = difficulty === 'hard' ? 6 : 4;
            const selectedOptions = colorEmojis.slice(0, numOptions);
            // 确保正确答案在选项中
            if (!selectedOptions.includes(colorEmojis[index])) {
              selectedOptions[0] = colorEmojis[index];
            }
            return {
              question: `选择 ${colors[index]}`,
              options: selectedOptions,
              answer: colorEmojis[index]
            };
          },
          () => {
            const colorMix = [
              { name: '橙色', mix: '红+黄', emoji: '🟠', options: ['🔴', '🟡', '🟠', '🟢'] },
              { name: '紫色', mix: '红+蓝', emoji: '🟣', options: ['🔴', '🔵', '🟣', '🟢'] },
              { name: '绿色', mix: '蓝+黄', emoji: '🟢', options: ['🔵', '🟡', '🟢', '🔴'] }
            ];
            const mix = colorMix[Math.floor(Math.random() * colorMix.length)];
            return {
              question: `${mix.mix} = ?`,
              options: mix.options,
              answer: mix.emoji
            };
          }
        ];
        const colorChallenge = colorChallenges[Math.floor(Math.random() * colorChallenges.length)]();
        return {
          id: round,
          type: 'color',
          category: '颜色识别',
          difficulty,
          question: colorChallenge.question,
          options: colorChallenge.options,
          correctAnswer: colorChallenge.answer,
          completed: false
        };
        
      case 'logic':
        const logicChallenges = [
          () => {
            const statements = [
              { premise: '所有猫都是动物，小花是猫', conclusion: '小花是动物', answer: '正确' },
              { premise: '有些鸟会飞，企鹅是鸟', conclusion: '企鹅会飞', answer: '错误' },
              { premise: '如果下雨，地面会湿', conclusion: '地面湿了，所以下雨了', answer: '错误' },
              { premise: '只有努力才能成功，小明成功了', conclusion: '小明努力了', answer: '正确' }
            ];
            const stmt = statements[Math.floor(Math.random() * statements.length)];
            return {
              question: `${stmt.premise}。结论：${stmt.conclusion}`,
              options: ['正确', '错误'],
              answer: stmt.answer
            };
          },
          () => {
            const puzzles = [
              { puzzle: 'A比B大，B比C大', question: '谁最大？', options: ['A', 'B', 'C'], answer: 'A' },
              { puzzle: '红球比蓝球重，蓝球比绿球重', question: '谁最轻？', options: ['红球', '蓝球', '绿球'], answer: '绿球' },
              { puzzle: '如果今天是周一，明天是？', question: '', options: ['周二', '周三', '周日'], answer: '周二' }
            ];
            const puzzle = puzzles[Math.floor(Math.random() * puzzles.length)];
            return {
              question: `${puzzle.puzzle}${puzzle.question ? ` ${puzzle.question}` : ''}`,
              options: puzzle.options,
              answer: puzzle.answer
            };
          }
        ];
        const logicChallenge = logicChallenges[Math.floor(Math.random() * logicChallenges.length)]();
        return {
          id: round,
          type: 'logic',
          category: '逻辑推理',
          difficulty,
          question: logicChallenge.question,
          options: logicChallenge.options,
          correctAnswer: logicChallenge.answer,
          completed: false
        };
        
      case 'word':
        const wordChallenges = [
          () => {
            const words = [
              { word: '快乐', opposite: '痛苦', options: ['痛苦', '高兴', '平静', '激动'] },
              { word: '温暖', opposite: '寒冷', options: ['寒冷', '凉爽', '热烈', '舒适'] },
              { word: '光明', opposite: '黑暗', options: ['黑暗', '明亮', '闪耀', '朦胧'] },
              { word: '勇敢', opposite: '胆怯', options: ['胆怯', '无畏', '坚强', '谨慎'] }
            ];
            const wordPair = words[Math.floor(Math.random() * words.length)];
            return {
              question: `"${wordPair.word}"的反义词是？`,
              options: wordPair.options,
              answer: wordPair.opposite
            };
          },
          () => {
            const analogies = [
              { analogy: '鸟:天空 = 鱼:?', options: ['水', '陆地', '空气', '树'], answer: '水' },
              { analogy: '医生:医院 = 老师:?', options: ['学校', '医院', '工厂', '商店'], answer: '学校' },
              { analogy: '手:写字 = 脚:?', options: ['走路', '跑步', '思考', '看书'], answer: '走路' }
            ];
            const analogy = analogies[Math.floor(Math.random() * analogies.length)];
            return {
              question: analogy.analogy,
              options: analogy.options,
              answer: analogy.answer
            };
          }
        ];
        const wordChallenge = wordChallenges[Math.floor(Math.random() * wordChallenges.length)]();
        return {
          id: round,
          type: 'word',
          category: '语言理解',
          difficulty,
          question: wordChallenge.question,
          options: wordChallenge.options,
          correctAnswer: wordChallenge.answer,
          completed: false
        };
        
      case 'sequence':
        const sequenceChallenges = [
          () => {
            const sequences = [
              { seq: [1, 1, 2, 3, 5], next: 8, type: '斐波那契' },
              { seq: [2, 6, 18, 54], next: 162, type: '乘3' },
              { seq: [100, 81, 64, 49], next: 36, type: '平方递减' },
              { seq: [1, 4, 9, 16], next: 25, type: '平方数' },
              { seq: [2, 4, 8, 16], next: 32, type: '乘2' },
              { seq: [3, 6, 12, 24], next: 48, type: '乘2' },
              { seq: [10, 20, 30, 40], next: 50, type: '加10' },
              { seq: [5, 10, 15, 20], next: 25, type: '加5' }
            ];
            const seqData = sequences[Math.floor(Math.random() * sequences.length)];
            // 生成合理的错误选项
            const wrongOptions = [];
            if (seqData.next > 10) {
              wrongOptions.push(seqData.next + Math.floor(seqData.next * 0.1));
              wrongOptions.push(seqData.next - Math.floor(seqData.next * 0.1));
              wrongOptions.push(Math.floor(seqData.next * 1.5));
            } else {
              wrongOptions.push(seqData.next + 1);
              wrongOptions.push(seqData.next + 2);
              wrongOptions.push(seqData.next - 1);
            }
            const uniqueWrongOptions = [...new Set(wrongOptions.filter(n => n > 0 && n !== seqData.next))];
            const allOptions = [seqData.next, ...uniqueWrongOptions.slice(0, 3)].sort(() => Math.random() - 0.5);
            return {
              question: `数列：${seqData.seq.join(', ')} → ?`,
              options: allOptions.map(String),
              answer: seqData.next.toString()
            };
          }
        ];
        const sequenceChallenge = sequenceChallenges[Math.floor(Math.random() * sequenceChallenges.length)]();
        return {
          id: round,
          type: 'sequence',
          category: '序列推理',
          difficulty,
          question: sequenceChallenge.question,
          options: sequenceChallenge.options,
          correctAnswer: sequenceChallenge.answer,
          completed: false
        };
        
      case 'calculation':
        const calculationChallenges = [
          () => {
            // 简单价格计算
            const item1Price = (Math.random() * 50 + 10).toFixed(2);
            const item2Price = (Math.random() * 30 + 5).toFixed(2);
            const total = (parseFloat(item1Price) + parseFloat(item2Price)).toFixed(2);
            // 生成干扰项
            const wrongOptions = [
              (parseFloat(total) + Math.random() * 2).toFixed(2),
              (parseFloat(total) - Math.random() * 2).toFixed(2),
              (parseFloat(total) + Math.random() * 5).toFixed(2)
            ];
            const allOptions = [total, ...wrongOptions].sort(() => Math.random() - 0.5);
            return {
              question: `商品A: ￥${item1Price}，商品B: ￥${item2Price}，总价格是？`,
              options: allOptions,
              answer: total // 注意这里不包含货币符号
            };
          },
          () => {
            // 折扣计算
            const originalPrice = Math.floor(Math.random() * 200) + 50;
            const discount = [0.1, 0.2, 0.3, 0.15, 0.25][Math.floor(Math.random() * 5)];
            const finalPrice = (originalPrice * (1 - discount)).toFixed(2);
            // 生成干扰项
            const wrongOptions = [
              (originalPrice * discount).toFixed(2), // 错误：只算折扣金额
              (originalPrice * (1 + discount)).toFixed(2), // 错误：加折扣
              (parseFloat(finalPrice) + Math.random() * 10).toFixed(2)
            ];
            const allOptions = [finalPrice, ...wrongOptions].sort(() => Math.random() - 0.5);
            return {
              question: `原价￥${originalPrice}，打${Math.floor((1 - discount) * 10)}折后价格是？`,
              options: allOptions,
              answer: finalPrice
            };
          },
          () => {
            // 税率计算  
            const basePrice = Math.floor(Math.random() * 100) + 20;
            const taxRate = 0.13; // 13%税率
            const finalPrice = (basePrice * (1 + taxRate)).toFixed(2);
            // 生成干扰项
            const wrongOptions = [
              (basePrice * taxRate).toFixed(2), // 错误：只算税额
              (basePrice * (1 + 0.1)).toFixed(2), // 错误：10%税率
              (parseFloat(finalPrice) - Math.random() * 5).toFixed(2)
            ];
            const allOptions = [finalPrice, ...wrongOptions].sort(() => Math.random() - 0.5);
            return {
              question: `商品价格￥${basePrice}，加13%税后总价是？`,
              options: allOptions,
              answer: finalPrice
            };
          }
        ];
        const calculationChallenge = calculationChallenges[Math.floor(Math.random() * calculationChallenges.length)]();
        return {
          id: round,
          type: 'calculation',
          category: '计算题',
          difficulty,
          question: calculationChallenge.question,
          options: calculationChallenge.options,
          correctAnswer: calculationChallenge.answer,
          completed: false
        };
        
      case 'spatial':
        const spatialChallenges = [
          () => {
            const shapes = ['⬆️', '⬇️', '⬅️', '➡️'];
            const rotations = [
              { shape: '⬆️', rotated: '➡️', desc: '顺时针90°' },
              { shape: '➡️', rotated: '⬇️', desc: '顺时针90°' },
              { shape: '⬇️', rotated: '⬅️', desc: '顺时针90°' },
              { shape: '⬅️', rotated: '⬆️', desc: '顺时针90°' }
            ];
            const rotation = rotations[Math.floor(Math.random() * rotations.length)];
            return {
              question: `${rotation.shape} 顺时针旋转90° = ?`,
              options: shapes,
              answer: rotation.rotated
            };
          },
          () => {
            const mirrorPairs = [
              { original: '◀️', mirrored: '▶️' },
              { original: '↖️', mirrored: '↗️' },
              { original: '↙️', mirrored: '↘️' }
            ];
            const pair = mirrorPairs[Math.floor(Math.random() * mirrorPairs.length)];
            // 确保选项包含所有可能的镜像答案
            const allMirrorOptions = ['◀️', '▶️', '↖️', '↗️', '↙️', '↘️'];
            return {
              question: `${pair.original} 的镜像是？`,
              options: allMirrorOptions,
              answer: pair.mirrored
            };
          }
        ];
        const spatialChallenge = spatialChallenges[Math.floor(Math.random() * spatialChallenges.length)]();
        return {
          id: round,
          type: 'spatial',
          category: '空间推理',
          difficulty,
          question: spatialChallenge.question,
          options: spatialChallenge.options,
          correctAnswer: spatialChallenge.answer,
          completed: false
        };
        
      case 'attention':
        const attentionChallenges = [
          () => {
            const chars = ['A', 'B', 'C', 'D'];
            const target = chars[Math.floor(Math.random() * chars.length)];
            const sequence = Array.from({ length: difficulty === 'hard' ? 8 : 6 }, 
              () => Math.random() < 0.3 ? target : chars[Math.floor(Math.random() * chars.length)]);
            const count = sequence.filter(c => c === target).length;
            return {
              question: `数出字母 ${target} 的个数：${sequence.join(' ')}`,
              options: [count, count + 1, count - 1, count + 2].filter(n => n >= 0).slice(0, 4).map(String),
              answer: count.toString()
            };
          }
        ];
        const attentionChallenge = attentionChallenges[Math.floor(Math.random() * attentionChallenges.length)]();
        return {
          id: round,
          type: 'attention',
          category: '注意力测试',
          difficulty,
          question: attentionChallenge.question,
          options: attentionChallenge.options,
          correctAnswer: attentionChallenge.answer,
          completed: false
        };
        
      case 'comparison':
        const comparisonChallenges = [
          () => {
            const nums = Array.from({ length: 4 }, () => Math.floor(Math.random() * 100) + 1);
            const max = Math.max(...nums);
            return {
              question: `找出最大数：${nums.join(', ')}`,
              options: nums.map(String),
              answer: max.toString()
            };
          },
          () => {
            const items = [
              { name: '苹果', weight: 150, unit: 'g' },
              { name: '香蕉', weight: 120, unit: 'g' },
              { name: '橙子', weight: 200, unit: 'g' },
              { name: '葡萄', weight: 80, unit: 'g' }
            ];
            const selected = items.slice(0, 3);
            const heaviest = selected.reduce((a, b) => a.weight > b.weight ? a : b);
            return {
              question: `哪个最重？`,
              options: selected.map(item => `${item.name}(${item.weight}${item.unit})`),
              answer: `${heaviest.name}(${heaviest.weight}${heaviest.unit})`
            };
          }
        ];
        const comparisonChallenge = comparisonChallenges[Math.floor(Math.random() * comparisonChallenges.length)]();
        return {
          id: round,
          type: 'comparison',
          category: '比较分析',
          difficulty,
          question: comparisonChallenge.question,
          options: comparisonChallenge.options,
          correctAnswer: comparisonChallenge.answer,
          completed: false
        };
        
      case 'calculation':
        const calcChallenges = [
          () => {
            const prices = Array.from({ length: 3 }, () => (Math.random() * 50 + 10).toFixed(2));
            const total = prices.reduce((sum, price) => sum + parseFloat(price), 0).toFixed(2);
            return {
              question: `计算总价：￥${prices.join(' + ￥')} = ?`,
              options: [total, (parseFloat(total) + 1).toFixed(2), (parseFloat(total) - 1).toFixed(2), (parseFloat(total) + 0.5).toFixed(2)],
              answer: `￥${total}`
            };
          },
          () => {
            const percent = [10, 15, 20, 25][Math.floor(Math.random() * 4)];
            const price = Math.floor(Math.random() * 200) + 100;
            const discount = (price * (100 - percent) / 100).toFixed(2);
            return {
              question: `原价￥${price}，打${(100-percent)/10}折，现价？`,
              options: [`￥${discount}`, `￥${(price * 0.8).toFixed(2)}`, `￥${(price * 0.9).toFixed(2)}`, `￥${(price * 0.7).toFixed(2)}`],
              answer: `￥${discount}`
            };
          }
        ];
        const calcChallenge = calcChallenges[Math.floor(Math.random() * calcChallenges.length)]();
        return {
          id: round,
          type: 'calculation',
          category: '计算应用',
          difficulty,
          question: calcChallenge.question,
          options: calcChallenge.options,
          correctAnswer: calcChallenge.answer,
          completed: false
        };
        
      default:
        return generateChallenge(round, isTeamMode);
    }
  };

  // AI答题逻辑 - 根据AI专长和题目类型调整表现
  const generateAIAnswer = (challenge: Challenge): { answer: string | number; time: number } => {
    let baseTime = 1000 + Math.random() * 2000;
    let difficultyMultiplier = 1 - (selectedAI?.difficulty || 0.5) * 0.5;
    let errorRate = 1 - (selectedAI?.difficulty || 0.5);
    
    // 根据AI专长调整表现
    if (selectedAI?.specialties) {
      const specialtyBonus = getSpecialtyBonus(challenge.category, selectedAI.specialties);
      difficultyMultiplier *= (1 - specialtyBonus * 0.3); // 专长题目用时减少
      errorRate *= (1 - specialtyBonus * 0.4); // 专长题目错误率降低
    }
    
    // 根据题目难度调整
    const difficultyFactor = {
      'easy': 0.8,
      'medium': 1.0,
      'hard': 1.3
    }[challenge.difficulty] || 1.0;
    
    baseTime *= difficultyFactor;
    errorRate *= difficultyFactor;
    
    // 反应测试特殊处理
    if (challenge.type === 'reaction') {
      baseTime = 300 + Math.random() * 800; // 反应测试用时更短
      errorRate *= 0.5; // 反应测试错误率更低
    }
    
    const actualTime = baseTime * difficultyMultiplier;
    const willMakeError = Math.random() < Math.min(0.4, errorRate); // 错误率上限40%
    
    // 如果有选项，优先从选项中选择答案
    if (challenge.options && challenge.options.length > 0) {
      if (willMakeError) {
        // 选择错误答案：从选项中排除正确答案
        const wrongOptions = challenge.options.filter(opt => 
          String(opt) !== String(challenge.correctAnswer)
        );
        if (wrongOptions.length > 0) {
          return {
            answer: wrongOptions[Math.floor(Math.random() * wrongOptions.length)],
            time: actualTime
          };
        }
      }
      
      // 确保正确答案在选项中，如果不在则从选项中随机选择一个
      if (challenge.options.includes(String(challenge.correctAnswer))) {
        return {
          answer: challenge.correctAnswer,
          time: actualTime
        };
      } else {
        // 如果正确答案不在选项中，从选项中随机选择
        console.warn('正确答案不在选项中，随机选择:', challenge.correctAnswer, challenge.options);
        return {
          answer: challenge.options[Math.floor(Math.random() * challenge.options.length)],
          time: actualTime
        };
      }
    }
    
    // 对于数值类型的错误答案（没有选项的情况）
    if (willMakeError && typeof challenge.correctAnswer === 'number') {
      const deviation = Math.floor(Math.random() * 10) + 1;
      const wrongAnswer = Math.random() > 0.5 ? 
        challenge.correctAnswer + deviation : 
        Math.max(0, challenge.correctAnswer - deviation);
      return {
        answer: wrongAnswer,
        time: actualTime
      };
    }
    
    // 默认返回正确答案
    return {
      answer: challenge.correctAnswer,
      time: actualTime
    };
  };
  
  // 获取AI在特定类别的专长加成
  const getSpecialtyBonus = (category: string, specialties: string[]): number => {
    const categoryMapping: Record<string, string[]> = {
      '反应速度': ['基础反应', '快速决策', '反应速度', '动作协调'],
      '记忆测试': ['基础反应', '简单逻辑'],
      '数学计算': ['简单逻辑', '策略规划'],
      '计算应用': ['简单逻辑', '策略规划'],
      '模式识别': ['逻辑推理', '策略规划', '模式识别'],
      '颜色识别': ['基础反应', '模式识别'],
      '逻辑推理': ['逻辑推理', '策略规划', '适应性学习'],
      '语言理解': ['逻辑推理', '适应性学习'],
      '序列推理': ['逻辑推理', '模式识别', '策略规划'],
      '空间推理': ['模式识别', '策略规划'],
      '注意力测试': ['快速决策', '反应速度', '完美执行'],
      '比较分析': ['策略规划', '适应性学习']
    };
    
    const relevantSpecialties = categoryMapping[category] || [];
    const matchCount = specialties.filter(specialty => 
      relevantSpecialties.some(relevant => specialty.includes(relevant) || relevant.includes(specialty))
    ).length;
    
    return Math.min(1.0, matchCount * 0.5); // 最大50%加成
  };

  // 开始单人对战
  const startSoloBattle = (ai: AIOpponent) => {
    setSelectedAI(ai);
    setPhase('preparation');
    setPreparationCountdown(5);
    setBattleStats({
      playerScore: 0,
      aiScore: 0,
      round: 1,
      totalRounds: 5,
      timeRemaining: 15,
      playerCorrect: 0,
      aiCorrect: 0
    });
    
    // 开始倒计时
    startPreparationCountdown();
  };

  // 开始团队对战
  const startTeamBattle = (ai: AIOpponent) => {
    setSelectedAI(ai);
    setBattleMode('team');
    setPhase('preparation');
    setPreparationCountdown(5);
    setTeamBattleStats({
      playerTeamScore: 0,
      aiTeamScore: 0,
      round: 1,
      totalRounds: 6,
      timeRemaining: 20,
      playerTeamCorrect: 0,
      aiTeamCorrect: 0,
      currentPlayerIndex: 0,
      completedChallenges: []
    });
    
    // 开始倒计时
    startPreparationCountdown();
  };

  // 开始准备倒计时 - 使用精确时间计算
  const startPreparationCountdown = () => {
    const startTime = Date.now();
    setPreparationStartTime(startTime);
    
    const countdownTimer = setInterval(() => {
      const elapsed = Date.now() - startTime;
      const remaining = Math.max(0, 5 - Math.floor(elapsed / 1000));
      
      setPreparationCountdown(remaining);
      
      if (remaining <= 0) {
        clearInterval(countdownTimer);
        // 倒计时结束，开始对战
        setPhase('battle');
        setBattleStarted(true);
        setPreparationStartTime(null);
        if (battleMode === 'team') {
          startNewTeamRound();
        } else {
          startNewRound();
        }
      }
    }, 100); // 使用100ms间隔进行更精确的检查
    
    // 立即执行一次以避免初始延迟
    const elapsed = Date.now() - startTime;
    const remaining = Math.max(0, 5 - Math.floor(elapsed / 1000));
    setPreparationCountdown(remaining);
  };

  // 开始新回合
  const startNewRound = () => {
    const challenge = generateChallenge(battleStats.round, false);
    setCurrentChallenge(challenge);
    setShowPlayerAnswer(false);
    setShowAIAnswer(false);
    setAiStatus('thinking');
    setAiThinkingProgress(0);
    setAiAnswerTime(null);
    setBattleStats(prev => ({ ...prev, timeRemaining: 15 }));
    
    // 记录挑战开始时间（用于准确计算用户答题时间）
    const challengeStart = Date.now();
    setChallengeStartTime(challengeStart);
    
    if (challenge.type === 'reaction') {
      const delay = 2000 + Math.random() * 3000;
      setTimeout(() => {
        setReactionStartTime(Date.now());
      }, delay);
    }
    
    // 生成AI答案时确保答案有效
    const aiResult = generateAIAnswer(challenge);
    
    // 验证AI答案是否有效
    if (challenge.options && !challenge.options.includes(String(aiResult.answer))) {
      console.warn('AI答案无效，重新生成:', aiResult.answer, '可选项:', challenge.options);
      // 如果AI答案无效，从选项中随机选择一个
      const randomOption = challenge.options[Math.floor(Math.random() * challenge.options.length)];
      aiResult.answer = randomOption;
    }
    
    const startTime = Date.now();
    
    // 模拟AI思考进度
    const thinkingInterval = setInterval(() => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min((elapsed / aiResult.time) * 100, 100);
      setAiThinkingProgress(progress);
      
      if (progress >= 100) {
        clearInterval(thinkingInterval);
        setAiStatus('answering');
      }
    }, 50);
    
    setTimeout(() => {
      setCurrentChallenge(prev => prev ? { ...prev, aiAnswer: aiResult.answer } : null);
      setShowAIAnswer(true);
      setAiStatus('completed');
      setAiAnswerTime(aiResult.time / 1000);
      clearInterval(thinkingInterval);
    }, aiResult.time);
  };

  // 开始新团队回合
  const startNewTeamRound = () => {
    const challenge = generateChallenge(teamBattleStats.round, true);
    setCurrentChallenge(challenge);
    setShowPlayerAnswer(false);
    setShowAIAnswer(false);
    setAiStatus('thinking');
    setAiThinkingProgress(0);
    setAiAnswerTime(null);
    setTeamBattleStats(prev => ({ ...prev, timeRemaining: 20 }));
    
    // 记录挑战开始时间（用于准确计算用户答题时间）
    const challengeStart = Date.now();
    setChallengeStartTime(challengeStart);
    
    if (challenge.type === 'reaction') {
      const delay = 2000 + Math.random() * 4000;
      setTimeout(() => {
        setReactionStartTime(Date.now());
      }, delay);
    }
    
    // 生成AI答案时确保答案有效
    const aiResult = generateAIAnswer(challenge);
    
    // 验证AI答案是否有效
    if (challenge.options && !challenge.options.includes(String(aiResult.answer))) {
      console.warn('AI答案无效，重新生成:', aiResult.answer, '可选项:', challenge.options);
      // 如果AI答案无效，从选项中随机选择一个
      const randomOption = challenge.options[Math.floor(Math.random() * challenge.options.length)];
      aiResult.answer = randomOption;
    }
    
    const startTime = Date.now();
    
    // 模拟AI思考进度
    const thinkingInterval = setInterval(() => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min((elapsed / aiResult.time) * 100, 100);
      setAiThinkingProgress(progress);
      
      if (progress >= 100) {
        clearInterval(thinkingInterval);
        setAiStatus('answering');
      }
    }, 50);
    
    setTimeout(() => {
      setCurrentChallenge(prev => prev ? { ...prev, aiAnswer: aiResult.answer } : null);
      setShowAIAnswer(true);
      setAiStatus('completed');
      setAiAnswerTime(aiResult.time / 1000);
      clearInterval(thinkingInterval);
    }, aiResult.time);
  };

  // 处理玩家答题
  const handleAnswer = (answer: string | number) => {
    if (!currentChallenge) return;
    
    let timeToAnswer = 0;
    
    if (currentChallenge.type === 'reaction' && reactionStartTime) {
      // 反应测试：从反应开始信号出现时计时
      timeToAnswer = (Date.now() - reactionStartTime) / 1000;
    } else if (challengeStartTime) {
      // 其他测试：从挑战开始时计时
      timeToAnswer = (Date.now() - challengeStartTime) / 1000;
    } else {
      // 备用计算方式（不应该发生）
      timeToAnswer = battleMode === 'team' ? 
        20 - teamBattleStats.timeRemaining : 
        15 - battleStats.timeRemaining;
    }
    
    setCurrentChallenge(prev => prev ? { 
      ...prev, 
      playerAnswer: answer,
      timeToAnswer,
      completed: true 
    } : null);
    setShowPlayerAnswer(true);
    
    const isCorrect = answer === currentChallenge.correctAnswer;
    const basePoints = battleMode === 'team' ? 25 : 20;
    const points = isCorrect ? 
      (currentChallenge.type === 'reaction' ? 
        Math.max(10, basePoints + 15 - timeToAnswer * 2) : 
        basePoints) : 0;
    
    if (battleMode === 'team') {
      setTeamBattleStats(prev => ({
        ...prev,
        playerTeamScore: prev.playerTeamScore + points,
        playerTeamCorrect: prev.playerTeamCorrect + (isCorrect ? 1 : 0)
      }));
    } else {
      setBattleStats(prev => ({
        ...prev,
        playerScore: prev.playerScore + points,
        playerCorrect: prev.playerCorrect + (isCorrect ? 1 : 0)
      }));
    }
    
    setTimeout(() => {
      const aiIsCorrect = currentChallenge.aiAnswer === currentChallenge.correctAnswer;
      const aiPoints = aiIsCorrect ? basePoints : 0;
      
      if (battleMode === 'team') {
        setTeamBattleStats(prev => ({
          ...prev,
          aiTeamScore: prev.aiTeamScore + aiPoints,
          aiTeamCorrect: prev.aiTeamCorrect + (aiIsCorrect ? 1 : 0)
        }));
        
        setTimeout(() => {
          if (teamBattleStats.round >= teamBattleStats.totalRounds) {
            finishBattle();
          } else {
            setTeamBattleStats(prev => ({ ...prev, round: prev.round + 1 }));
            startNewTeamRound();
          }
        }, 2000);
      } else {
        setBattleStats(prev => ({
          ...prev,
          aiScore: prev.aiScore + aiPoints,
          aiCorrect: prev.aiCorrect + (aiIsCorrect ? 1 : 0)
        }));
        
        setTimeout(() => {
          if (battleStats.round >= battleStats.totalRounds) {
            finishBattle();
          } else {
            setBattleStats(prev => ({ ...prev, round: prev.round + 1 }));
            startNewRound();
          }
        }, 2000);
      }
    }, 1000);
  };

  // 搜索匹配计时器
  useEffect(() => {
    if (isSearching) {
      const searchTimer = setInterval(() => {
        setSearchTime(prev => {
          if (prev >= 30) {
            setMatchFound(true);
            setIsSearching(false);
            return 0;
          }
          return prev + 1;
        });
      }, 1000);

      return () => clearInterval(searchTimer);
    }
  }, [isSearching]);

  // 对战计时器
  useEffect(() => {
    if (battleStarted && phase === 'battle' && !currentChallenge?.completed) {
      let timeRemaining;
      if (pvpMode === 'battle') {
        timeRemaining = pvpBattleStats.timeRemaining;
      } else if (battleMode === 'team') {
        timeRemaining = teamBattleStats.timeRemaining;
      } else {
        timeRemaining = battleStats.timeRemaining;
      }
        
      if (timeRemaining > 0) {
        timerRef.current = setTimeout(() => {
          if (pvpMode === 'battle') {
            setPvpBattleStats(prev => ({
              ...prev,
              timeRemaining: prev.timeRemaining - 1
            }));
          } else if (battleMode === 'team') {
            setTeamBattleStats(prev => ({
              ...prev,
              timeRemaining: prev.timeRemaining - 1
            }));
          } else {
            setBattleStats(prev => ({
              ...prev,
              timeRemaining: prev.timeRemaining - 1
            }));
          }
        }, 1000);
      } else {
        // 处理超时情况
        if (currentChallenge && !currentChallenge.completed) {
          let timeToAnswer = 0;
          if (challengeStartTime) {
            timeToAnswer = (Date.now() - challengeStartTime) / 1000;
          } else {
            timeToAnswer = battleMode === 'team' ? 20 : 15;
          }
          
          setCurrentChallenge(prev => prev ? { 
            ...prev, 
            playerAnswer: 'timeout',
            timeToAnswer,
            completed: true 
          } : null);
          setShowPlayerAnswer(true);
          
          // 继续执行原有的答题后逻辑
          const isCorrect = false; // 超时总是错误
          const basePoints = battleMode === 'team' ? 25 : 20;
          const points = 0; // 超时得分为0
          
          if (battleMode === 'team') {
            setTeamBattleStats(prev => ({
              ...prev,
              playerTeamScore: prev.playerTeamScore + points,
              playerTeamCorrect: prev.playerTeamCorrect + (isCorrect ? 1 : 0)
            }));
          } else {
            setBattleStats(prev => ({
              ...prev,
              playerScore: prev.playerScore + points,
              playerCorrect: prev.playerCorrect + (isCorrect ? 1 : 0)
            }));
          }
          
          setTimeout(() => {
            const aiIsCorrect = currentChallenge.aiAnswer === currentChallenge.correctAnswer;
            const aiPoints = aiIsCorrect ? basePoints : 0;
            
            if (battleMode === 'team') {
              setTeamBattleStats(prev => ({
                ...prev,
                aiTeamScore: prev.aiTeamScore + aiPoints,
                aiTeamCorrect: prev.aiTeamCorrect + (aiIsCorrect ? 1 : 0)
              }));
              
              setTimeout(() => {
                if (teamBattleStats.round >= teamBattleStats.totalRounds) {
                  finishBattle();
                } else {
                  setTeamBattleStats(prev => ({ ...prev, round: prev.round + 1 }));
                  startNewTeamRound();
                }
              }, 2000);
            } else {
              setBattleStats(prev => ({
                ...prev,
                aiScore: prev.aiScore + aiPoints,
                aiCorrect: prev.aiCorrect + (aiIsCorrect ? 1 : 0)
              }));
              
              setTimeout(() => {
                if (battleStats.round >= battleStats.totalRounds) {
                  finishBattle();
                } else {
                  setBattleStats(prev => ({ ...prev, round: prev.round + 1 }));
                  startNewRound();
                }
              }, 2000);
            }
          }, 1000);
        }
      }
    }

    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, [battleStarted, battleStats.timeRemaining, teamBattleStats.timeRemaining, pvpBattleStats.timeRemaining, phase, currentChallenge?.completed, battleMode, pvpMode]);

  const finishBattle = () => {
    setBattleStarted(false);
    
    let currentStats, playerScore, opponentScore, correctAnswers, totalRounds, testTypeName;
    
    if (pvpMode === 'battle') {
      // PvP对战
      currentStats = pvpBattleStats;
      playerScore = currentStats.player1Score;
      opponentScore = currentStats.player2Score;
      correctAnswers = currentStats.player1Correct;
      totalRounds = currentStats.totalRounds;
      testTypeName = '真人对战';
    } else if (battleMode === 'team') {
      // 团队对战
      currentStats = teamBattleStats;
      playerScore = currentStats.playerTeamScore;
      opponentScore = currentStats.aiTeamScore;
      correctAnswers = currentStats.playerTeamCorrect;
      totalRounds = currentStats.totalRounds;
      testTypeName = 'AI团队对战';
    } else {
      // 单人AI对战
      currentStats = battleStats;
      playerScore = currentStats.playerScore;
      opponentScore = currentStats.aiScore;
      correctAnswers = currentStats.playerCorrect;
      totalRounds = currentStats.totalRounds;
      testTypeName = 'AI对战综合测试';
    }
    
    const playerWins = playerScore > opponentScore;
    const isDraw = playerScore === opponentScore;
    
    const result = playerWins ? 'victory' : isDraw ? 'draw' : 'defeat';
    setBattleResult(result);
    setPhase('result');
    
    const finalScore = Math.min(100, Math.round((correctAnswers / totalRounds) * 100));
    const testResult: TestResult = {
      id: Date.now().toString(),
      testType: testTypeName,
      score: finalScore,
      maxScore: 100,
      date: new Date(),
      duration: totalRounds * (pvpMode === 'battle' ? 15 : battleMode === 'team' ? 20 : 15),
      percentile: Math.max(1, Math.min(99, finalScore + Math.random() * 20 - 10)),
      details: {
        battleMode: true,
        pvpMode: pvpMode === 'battle',
        teamMode: battleMode === 'team',
        opponent: pvpMode === 'battle' ? opponent?.id : selectedAI!.id,
        winner: playerWins ? 'player' : 'opponent',
        rounds: totalRounds,
        playerScore: playerScore,
        opponentScore: opponentScore,
        playerCorrect: correctAnswers,
        opponentCorrect: pvpMode === 'battle' ? currentStats.player2Correct : 
                       battleMode === 'team' ? (currentStats as TeamBattleStats).aiTeamCorrect : 
                       (currentStats as BattleStats).aiCorrect
      }
    };

    // 保存测试结果，让用户手动选择
    setFinalTestResult(testResult);
  };

  const resetBattle = () => {
    setPhase('selection');
    setSelectedAI(null);
    setBattleStarted(false);
    setBattleResult(null);
    setFinalTestResult(null);
    setCurrentChallenge(null);
    setReactionStartTime(null);
    setChallengeStartTime(null);
    setBattleMode('solo');
    setPreparationCountdown(5);
    setPreparationStartTime(null);
    
    // 重置AI状态
    setAiStatus('waiting');
    setAiThinkingProgress(0);
    setAiAnswerTime(null);
    
    // 重置PvP状态
    setPvpMode('matchmaking');
    setIsSearching(false);
    setSearchTime(0);
    setMatchFound(false);
    setCurrentRoom(null);
    setOpponent(null);
    
    setBattleStats({
      playerScore: 0,
      aiScore: 0,
      round: 1,
      totalRounds: 5,
      timeRemaining: 15,
      playerCorrect: 0,
      aiCorrect: 0
    });
    setTeamBattleStats({
      playerTeamScore: 0,
      aiTeamScore: 0,
      round: 1,
      totalRounds: 6,
      timeRemaining: 20,
      playerTeamCorrect: 0,
      aiTeamCorrect: 0,
      currentPlayerIndex: 0,
      completedChallenges: []
    });
    setPvpBattleStats({
      player1Score: 0,
      player2Score: 0,
      player1Correct: 0,
      player2Correct: 0,
      round: 1,
      totalRounds: 5,
      timeRemaining: 15,
      currentQuestion: 1
    });
  };

  // 准备阶段组件
  if (phase === 'preparation') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/50 to-indigo-50">
        <div className="container mx-auto px-4 py-8">
          {/* 准备阶段顶部返回区域 */}
          <div className="flex items-center justify-between mb-6">
            <motion.div
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
            >
              <Button 
                variant="ghost" 
                onClick={() => {
                  setPhase('selection');
                  setSelectedAI(null);
                  setBattleMode('solo');
                  setPreparationCountdown(5);
                  setPreparationStartTime(null);
                }}
                className="flex items-center gap-2 text-slate-600 hover:text-slate-800 hover:bg-slate-100 transition-all duration-200"
                disabled={preparationCountdown <= 1}
              >
                <ArrowLeft className="w-4 h-4" />
                返回对战选择
              </Button>
            </motion.div>
            
            <div className="flex items-center gap-2">
              <Badge variant="outline" className="px-3 py-1">
                {battleMode === 'team' ? '团队模式' : '单人模式'}
              </Badge>
              <Badge variant="outline" className="px-3 py-1 bg-orange-50 text-orange-600 border-orange-200">
                对战准备中
              </Badge>
            </div>
          </div>

          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.5 }}
            className="flex items-center justify-center min-h-[60vh]"
          >
            <Card className="w-full max-w-2xl bg-white/90 backdrop-blur-sm border-2 border-blue-200 shadow-2xl">
              <CardContent className="p-12 text-center space-y-8">
                {/* 对手信息 */}
                <motion.div
                  initial={{ y: -20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: 0.2, duration: 0.6 }}
                  className="space-y-4"
                >
                  <div className={`w-24 h-24 mx-auto rounded-full bg-gradient-to-br ${selectedAI?.bgGradient} border-4 border-white shadow-lg flex items-center justify-center text-4xl`}>
                    {selectedAI?.emoji}
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-slate-800 mb-2">
                      即将对战：{selectedAI?.name}
                    </h2>
                    <p className="text-slate-600 mb-3">{selectedAI?.description}</p>
                    <div className="flex justify-center gap-2">
                      {selectedAI?.specialties.map((specialty, index) => (
                        <Badge key={index} variant="secondary" className="text-xs">
                          {specialty}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </motion.div>

                {/* 对战模式信息 */}
                <motion.div
                  initial={{ y: 20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: 0.4, duration: 0.6 }}
                  className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-6 border border-blue-200"
                >
                  <h3 className="font-semibold text-lg mb-3 text-slate-800">
                    {battleMode === 'team' ? '🚀 团队对战模式' : '⚔️ 单人对战模式'}
                  </h3>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="flex items-center gap-2">
                      <Timer className="w-4 h-4 text-blue-600" />
                      <span>共 {battleMode === 'team' ? 6 : 5} 轮</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Zap className="w-4 h-4 text-yellow-600" />
                      <span>每轮 {battleMode === 'team' ? 20 : 15} 秒</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Target className="w-4 h-4 text-green-600" />
                      <span>混合题型</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Trophy className="w-4 h-4 text-purple-600" />
                      <span>实时计分</span>
                    </div>
                  </div>
                </motion.div>

                {/* 倒����� */}
                <motion.div
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  transition={{ delay: 0.6, duration: 0.4 }}
                  className="space-y-4"
                >
                  <p className="text-slate-600 font-medium">对战即将开始</p>
                  <motion.div
                    key={preparationCountdown}
                    initial={{ scale: 0.5, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 1.5, opacity: 0 }}
                    transition={{ duration: 0.3 }}
                    className="relative"
                  >
                    <div className="w-32 h-32 mx-auto rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center shadow-2xl">
                      <span className="text-6xl font-bold text-white">
                        {preparationCountdown || '🚀'}
                      </span>
                    </div>
                    {preparationCountdown > 0 && (
                      <motion.div
                        initial={{ scale: 1, opacity: 0.8 }}
                        animate={{ scale: 1.2, opacity: 0 }}
                        transition={{ 
                          duration: 1,
                          repeat: Infinity,
                          repeatType: "loop"
                        }}
                        className="absolute inset-0 rounded-full border-4 border-blue-400"
                      />
                    )}
                  </motion.div>
                  
                  {preparationCountdown > 0 ? (
                    <motion.p
                      key={`text-${preparationCountdown}`}
                      initial={{ y: 10, opacity: 0 }}
                      animate={{ y: 0, opacity: 1 }}
                      exit={{ y: -10, opacity: 0 }}
                      transition={{ duration: 0.3 }}
                      className="text-xl font-semibold text-slate-700"
                    >
                      {preparationCountdown === 5 && "准备就绪！"}
                      {preparationCountdown === 4 && "调整心态..."}
                      {preparationCountdown === 3 && "专注准备..."}
                      {preparationCountdown === 2 && "集中注意力..."}
                      {preparationCountdown === 1 && "即将开始！"}
                    </motion.p>
                  ) : (
                    <motion.p
                      initial={{ y: 10, opacity: 0 }}
                      animate={{ y: 0, opacity: 1 }}
                      transition={{ duration: 0.3 }}
                      className="text-xl font-bold text-transparent bg-gradient-to-r from-green-600 to-emerald-600 bg-clip-text"
                    >
                      开始对战！
                    </motion.p>
                  )}
                </motion.div>


              </CardContent>
            </Card>
          </motion.div>
        </div>
      </div>
    );
  }

  if (phase === 'selection') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/50 to-indigo-50">
        <div className="container mx-auto px-4 py-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
          >
            {/* Header */}
            <div className="flex flex-col items-center justify-center mb-8">
              <div className="w-full flex justify-start mb-4">
                <Button variant="ghost" onClick={onBack} className="flex items-center gap-2">
                  <ArrowLeft className="w-4 h-4" />
                  返回主页
                </Button>
              </div>
              <div className="flex items-center justify-center gap-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-600 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
                  <Swords className="w-6 h-6 text-white" />
                </div>
                <div className="text-center">
                  <h1 className="text-2xl font-bold bg-gradient-to-r from-blue-700 to-purple-700 bg-clip-text text-transparent">
                    AI智能对战中心
                  </h1>
                  <p className="text-slate-600">选择对战模式，挑战AI极限</p>
                </div>
              </div>
            </div>

            {/* Tabs */}
            <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as any)} className="space-y-6">
              <TabsList className="grid w-full grid-cols-4 bg-white/70 backdrop-blur-sm border border-slate-200 shadow-sm h-12 p-1">
                <TabsTrigger 
                  value="solo" 
                  className="flex items-center justify-center gap-2 h-10 px-3 py-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-purple-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all duration-200"
                >
                  <Gamepad2 className="w-4 h-4 flex-shrink-0" />
                  <span className="leading-none text-sm">单人对战</span>
                </TabsTrigger>
                <TabsTrigger 
                  value="team" 
                  className="flex items-center justify-center gap-2 h-10 px-3 py-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-purple-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all duration-200"
                >
                  <Users className="w-4 h-4 flex-shrink-0" />
                  <span className="leading-none text-sm">团队对战</span>
                </TabsTrigger>
                <TabsTrigger 
                  value="pvp" 
                  className="flex items-center justify-center gap-2 h-10 px-3 py-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-green-600 data-[state=active]:to-emerald-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all duration-200 relative"
                >
                  <UserPlus className="w-4 h-4 flex-shrink-0" />
                  <span className="leading-none text-sm">真人PK</span>
                  <div className="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full animate-pulse"></div>
                </TabsTrigger>
                <TabsTrigger 
                  value="leaderboard" 
                  className="flex items-center justify-center gap-2 h-10 px-3 py-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-yellow-600 data-[state=active]:to-orange-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all duration-200"
                >
                  <Trophy className="w-4 h-4 flex-shrink-0" />
                  <span className="leading-none text-sm">排行榜</span>
                </TabsTrigger>
              </TabsList>

              {/* Solo Battle Tab */}
              <TabsContent value="solo" className="space-y-6">
                {/* AI对手选择 */}
                <Card className="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Bot className="w-5 h-5 text-blue-600" />
                      选择AI对手
                    </CardTitle>
                    <CardDescription>
                      每个AI都有独特的个性和难度等级
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="grid md:grid-cols-2 gap-6">
                      {aiOpponents.map((ai) => (
                        <motion.div
                          key={ai.id}
                          whileHover={{ scale: 1.02 }}
                          whileTap={{ scale: 0.98 }}
                        >
                          <Card className="hover:shadow-lg bg-white/80 transition-all duration-300 border-2 hover:border-blue-200">
                            <CardContent className="p-6">
                              <div className="flex items-start justify-between gap-4">
                                <div className="flex items-start gap-4 flex-1">
                                  <div className="text-5xl">{ai.emoji}</div>
                                  <div className="flex-1">
                                    <div className="flex items-center gap-2 mb-2">
                                      <h3 className="text-lg font-semibold">{ai.name}</h3>
                                      <Badge variant="outline" className={ai.color}>
                                        Lv.{ai.level}
                                      </Badge>
                                      <Badge variant="secondary" className="text-xs bg-slate-100 text-slate-600">
                                        胜率: {Math.round(ai.difficulty * 100)}%
                                      </Badge>
                                    </div>
                                    <p className="text-sm text-slate-600 mb-2">{ai.description}</p>
                                    <p className="text-xs text-slate-500 mb-3">{ai.personality}</p>
                                    <div className="flex items-center gap-1 mb-3">
                                      {Array.from({ length: ai.level }, (_, i) => (
                                        <Star key={i} className="w-3 h-3 fill-yellow-400 text-yellow-400" />
                                      ))}
                                      <span className="text-xs text-slate-500 ml-2">
                                        AI强度 {ai.level}/4
                                      </span>
                                    </div>
                                    <div className="space-y-2">
                                      <p className="text-xs font-medium text-slate-700">擅长题型：</p>
                                      <div className="flex flex-wrap gap-1">
                                        {ai.specialties.map((specialty, index) => (
                                          <Badge key={index} variant="secondary" className="text-xs bg-blue-100 text-blue-700 border-blue-200">
                                            {specialty}
                                          </Badge>
                                        ))}
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div className="flex-shrink-0">
                                  <Button 
                                    onClick={() => startSoloBattle(ai)}
                                    variant="outline"
                                    size="sm"
                                    className="bg-gradient-to-r from-blue-50 to-purple-50 border-blue-200 text-blue-700 hover:bg-gradient-to-r hover:from-blue-100 hover:to-purple-100 hover:border-blue-300 px-4 transition-all duration-300"
                                  >
                                    <Play className="w-4 h-4 mr-1" />
                                    开始对战
                                  </Button>
                                </div>
                              </div>
                            </CardContent>
                          </Card>
                        </motion.div>
                      ))}
                    </div>
                  </CardContent>
                </Card>

                {/* 对战说明 */}
                <Card className="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
                  <CardContent className="p-6">
                    <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                      <Target className="w-5 h-5 text-blue-600" />
                      单人对战规则
                    </h3>
                    <div className="grid md:grid-cols-3 gap-4 text-sm mb-6">
                      <div className="flex items-start gap-2">
                        <Circle className="w-4 h-4 text-blue-500 mt-1 flex-shrink-0" />
                        <div>
                          <p className="font-medium">5轮挑战</p>
                          <p className="text-slate-600">12种题型随机出题，丰富多样</p>
                        </div>
                      </div>
                      <div className="flex items-start gap-2">
                        <Timer className="w-4 h-4 text-green-500 mt-1 flex-shrink-0" />
                        <div>
                          <p className="font-medium">限时答题</p>
                          <p className="text-slate-600">每题15秒，速度影响得分</p>
                        </div>
                      </div>
                      <div className="flex items-start gap-2">
                        <Trophy className="w-4 h-4 text-yellow-500 mt-1 flex-shrink-0" />
                        <div>
                          <p className="font-medium">智能匹配</p>
                          <p className="text-slate-600">AI根据专长出题，真实挑战</p>
                        </div>
                      </div>
                    </div>
                    
                    {/* 题型展示 */}
                    <div className="border-t border-blue-200/50 pt-4">
                      <h4 className="font-medium text-blue-700 mb-3">包含题型 (12种)</h4>
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
                        {[
                          { name: '反应速度', color: 'bg-red-100 text-red-600' },
                          { name: '记忆测试', color: 'bg-purple-100 text-purple-600' },
                          { name: '数学计算', color: 'bg-green-100 text-green-600' },
                          { name: '模式识别', color: 'bg-blue-100 text-blue-600' },
                          { name: '颜色识别', color: 'bg-yellow-100 text-yellow-600' },
                          { name: '逻辑推理', color: 'bg-indigo-100 text-indigo-600' },
                          { name: '语言理解', color: 'bg-pink-100 text-pink-600' },
                          { name: '序列推理', color: 'bg-teal-100 text-teal-600' },
                          { name: '空间推理', color: 'bg-orange-100 text-orange-600' },
                          { name: '注意力测试', color: 'bg-cyan-100 text-cyan-600' },
                          { name: '比较分析', color: 'bg-lime-100 text-lime-600' },
                          { name: '计算应用', color: 'bg-emerald-100 text-emerald-600' }
                        ].map((type, index) => (
                          <div key={index} className={`px-2 py-1 rounded-full text-center ${type.color}`}>
                            {type.name}
                          </div>
                        ))}
                      </div>
                      <p className="text-xs text-slate-500 mt-3">
                        💡 每种题型包含多个变种，AI会根据专长调整出题权重和难度
                      </p>
                    </div>
                  </CardContent>
                </Card>


              </TabsContent>

              {/* Team Battle Tab */}
              <TabsContent value="team" className="space-y-6">
                <div className="grid lg:grid-cols-2 gap-6">
                  {/* 团队配置 */}
                  <Card className="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <Users className="w-5 h-5 text-purple-600" />
                        组建战队
                      </CardTitle>
                      <CardDescription>
                        选择队伍规模和AI队友
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div>
                        <label className="text-sm font-medium mb-2 block">团队规模</label>
                        <div className="grid grid-cols-2 gap-3">
                          <Button
                            variant={selectedTeamSize === 2 ? "default" : "outline"}
                            onClick={() => setSelectedTeamSize(2)}
                            className={`h-16 transition-all duration-300 ${
                              selectedTeamSize === 2 
                                ? 'bg-slate-600 hover:bg-slate-700 text-white shadow-md border-0' 
                                : 'bg-white hover:bg-slate-50 border-slate-300 text-slate-700 hover:border-slate-400'
                            }`}
                          >
                            <div className="text-center">
                              <div className="text-lg">2v2</div>
                              <div className="text-xs opacity-80">小队模式</div>
                            </div>
                          </Button>
                          <Button
                            variant={selectedTeamSize === 3 ? "default" : "outline"}
                            onClick={() => setSelectedTeamSize(3)}
                            className={`h-16 transition-all duration-300 ${
                              selectedTeamSize === 3 
                                ? 'bg-slate-600 hover:bg-slate-700 text-white shadow-md border-0' 
                                : 'bg-white hover:bg-slate-50 border-slate-300 text-slate-700 hover:border-slate-400'
                            }`}
                          >
                            <div className="text-center">
                              <div className="text-lg">3v3</div>
                              <div className="text-xs opacity-80">团队模式</div>
                            </div>
                          </Button>
                        </div>
                      </div>

                      <div>
                        <label className="text-sm font-medium mb-2 block">你的队伍</label>
                        <div className="space-y-2">
                          {playerTeam.slice(0, selectedTeamSize).map((member, index) => (
                            <div key={index} className="flex items-center gap-3 p-3 bg-blue-50 rounded-lg">
                              <div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white text-sm font-semibold">
                                {index === 0 ? '你' : `A${index}`}
                              </div>
                              <span className="font-medium">{member}</span>
                              {index === 0 && (
                                <Badge variant="outline" className="ml-auto">队长</Badge>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* AI对手选择 */}
                  <Card className="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <Bot className="w-5 h-5 text-red-600" />
                        选择敌方AI团队
                      </CardTitle>
                      <CardDescription>
                        选择要对战的AI团队
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-4">
                        {aiOpponents.map((ai) => (
                          <motion.div
                            key={ai.id}
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98 }}
                          >
                            <Card className="hover:shadow-lg bg-white/80 transition-all duration-300">
                              <CardContent className="p-4">
                                <div className="flex items-center justify-between gap-4">
                                  <div className="flex items-center gap-3 flex-1">
                                    <div className="text-3xl">{ai.emoji}</div>
                                    <div className="flex-1">
                                      <div className="flex items-center gap-2 mb-1">
                                        <h3 className="font-semibold">{ai.name}团队</h3>
                                        <Badge variant="outline" className={ai.color}>
                                          {selectedTeamSize}v{selectedTeamSize}
                                        </Badge>
                                      </div>
                                      <p className="text-sm text-slate-600 mb-2">{ai.description}</p>
                                      <div className="flex items-center gap-1">
                                        {Array.from({ length: ai.level }, (_, i) => (
                                          <Star key={i} className="w-3 h-3 fill-yellow-400 text-yellow-400" />
                                        ))}
                                      </div>
                                    </div>
                                  </div>
                                  <div className="flex-shrink-0">
                                    <Button 
                                      onClick={() => startTeamBattle(ai)}
                                      variant="outline"
                                      size="sm"
                                      className="bg-slate-50 border-slate-200 text-slate-700 hover:bg-slate-100 hover:text-slate-900 px-4"
                                    >
                                      <Users className="w-4 h-4 mr-1" />
                                      开始对战
                                    </Button>
                                  </div>
                                </div>
                              </CardContent>
                            </Card>
                          </motion.div>
                        ))}
                      </div>
                    </CardContent>
                  </Card>
                </div>

                {/* 团队对战说明 */}
                <Card className="bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200">
                  <CardContent className="p-6">
                    <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                      <Users className="w-5 h-5 text-purple-600" />
                      团队对战规则
                    </h3>
                    <div className="grid md:grid-cols-3 gap-4 text-sm mb-6">
                      <div className="flex items-start gap-2">
                        <Circle className="w-4 h-4 text-purple-500 mt-1 flex-shrink-0" />
                        <div>
                          <p className="font-medium">6轮团队挑战</p>
                          <p className="text-slate-600">更高难度，题目更复杂</p>
                        </div>
                      </div>
                      <div className="flex items-start gap-2">
                        <Timer className="w-4 h-4 text-green-500 mt-1 flex-shrink-0" />
                        <div>
                          <p className="font-medium">每题20秒</p>
                          <p className="text-slate-600">更多时间思考策略</p>
                        </div>
                      </div>
                      <div className="flex items-start gap-2">
                        <Trophy className="w-4 h-4 text-yellow-500 mt-1 flex-shrink-0" />
                        <div>
                          <p className="font-medium">团队积分</p>
                          <p className="text-slate-600">所有成员贡献分数</p>
                        </div>
                      </div>
                    </div>
                    
                    {/* 团队模式特色 */}
                    <div className="border-t border-purple-200/50 pt-4">
                      <h4 className="font-medium text-purple-700 mb-3">团队模式特色</h4>
                      <div className="grid grid-cols-2 gap-3 text-sm">
                        <div className="flex items-center gap-2">
                          <div className="w-2 h-2 bg-purple-500 rounded-full"></div>
                          <span>题目难度自动提升</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <div className="w-2 h-2 bg-pink-500 rounded-full"></div>
                          <span>序列长度增加</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <div className="w-2 h-2 bg-purple-500 rounded-full"></div>
                          <span>数学运算更复杂</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <div className="w-2 h-2 bg-pink-500 rounded-full"></div>
                          <span>更多选项和干扰项</span>
                        </div>
                      </div>
                      <p className="text-xs text-slate-500 mt-3">
                        🚀 团队模式会优先选择更有挑战性的题型，考验团队协作能力
                      </p>
                    </div>
                  </CardContent>
                </Card>


              </TabsContent>

              {/* PvP Matchmaking Tab */}
              <TabsContent value="pvp" className="space-y-6">
                <div className="grid gap-6">
                  {/* PvP Mode Selection */}
                  <div className="flex gap-2 p-1 bg-gray-100 rounded-lg">
                    <button
                      onClick={() => setPvpMode('matchmaking')}
                      className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-md transition-all ${
                        pvpMode === 'matchmaking'
                          ? 'bg-white shadow-sm text-gray-900'
                          : 'text-gray-600 hover:text-gray-900'
                      }`}
                    >
                      <Search className="w-4 h-4" />
                      匹配对战
                    </button>
                    <button
                      onClick={() => setPvpMode('rooms')}
                      className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-md transition-all ${
                        pvpMode === 'rooms'
                          ? 'bg-white shadow-sm text-gray-900'
                          : 'text-gray-600 hover:text-gray-900'
                      }`}
                    >
                      <Users className="w-4 h-4" />
                      房间对战
                    </button>
                    <button
                      onClick={() => setPvpMode('friends')}
                      className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-md transition-all ${
                        pvpMode === 'friends'
                          ? 'bg-white shadow-sm text-gray-900'
                          : 'text-gray-600 hover:text-gray-900'
                      }`}
                    >
                      <Heart className="w-4 h-4" />
                      好友对战
                    </button>
                  </div>

                  {/* Matchmaking Content */}
                  {pvpMode === 'matchmaking' && (
                    <div className="space-y-6">
                      {!isSearching && !matchFound ? (
                        <div className="space-y-6">
                          {/* Match Settings */}
                          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                            {/* Match Mode */}
                            <motion.div
                              initial={{ opacity: 0, y: 20 }}
                              animate={{ opacity: 1, y: 0 }}
                              transition={{ duration: 0.3 }}
                            >
                              <Card className="h-full bg-white/80 backdrop-blur-sm border border-slate-200 shadow-sm hover:shadow-md transition-all duration-300">
                                <CardHeader className="pb-3">
                                  <CardTitle className="flex items-center gap-3 text-gray-700">
                                    <div className="w-8 h-8 bg-gradient-to-br from-gray-100 to-gray-200 rounded-lg flex items-center justify-center">
                                      <Trophy className="w-4 h-4 text-gray-600" />
                                    </div>
                                    匹配模式
                                  </CardTitle>
                                  <CardDescription className="text-gray-500">
                                    选择你的对战类型
                                  </CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-3">
                                  <motion.div
                                    whileHover={{ scale: 1.02 }}
                                    whileTap={{ scale: 0.98 }}
                                    className={`p-4 border rounded-xl cursor-pointer transition-all duration-200 ${
                                      matchSettings.mode === 'ranked'
                                        ? 'border-gray-400 bg-gray-50 shadow-sm'
                                        : 'border-gray-200 hover:border-gray-300 hover:bg-gray-25'
                                    }`}
                                    onClick={() => setMatchSettings(prev => ({ ...prev, mode: 'ranked' }))}
                                  >
                                    <div className="flex items-start gap-3">
                                      <div className="w-10 h-10 bg-gradient-to-br from-gray-200 to-gray-300 rounded-lg flex items-center justify-center flex-shrink-0">
                                        <Trophy className="w-5 h-5 text-gray-600" />
                                      </div>
                                      <div className="flex-1">
                                        <div className="font-semibold text-gray-800">排位赛</div>
                                        <div className="text-sm text-gray-600 mt-1">参与排名竞争，影响积分等级</div>
                                        <div className="text-xs text-gray-500 mt-2 flex items-center gap-1">
                                          <Star className="w-3 h-3" />
                                          高质量匹配
                                        </div>
                                      </div>
                                      {matchSettings.mode === 'ranked' && (
                                        <motion.div
                                          initial={{ scale: 0 }}
                                          animate={{ scale: 1 }}
                                          className="w-5 h-5 bg-gray-600 rounded-full flex items-center justify-center"
                                        >
                                          <Check className="w-3 h-3 text-white" />
                                        </motion.div>
                                      )}
                                    </div>
                                  </motion.div>
                                  
                                  <motion.div
                                    whileHover={{ scale: 1.02 }}
                                    whileTap={{ scale: 0.98 }}
                                    className={`p-4 border rounded-xl cursor-pointer transition-all duration-200 ${
                                      matchSettings.mode === 'casual'
                                        ? 'border-gray-400 bg-gray-50 shadow-sm'
                                        : 'border-gray-200 hover:border-gray-300 hover:bg-gray-25'
                                    }`}
                                    onClick={() => setMatchSettings(prev => ({ ...prev, mode: 'casual' }))}
                                  >
                                    <div className="flex items-start gap-3">
                                      <div className="w-10 h-10 bg-gradient-to-br from-gray-200 to-gray-300 rounded-lg flex items-center justify-center flex-shrink-0">
                                        <Gamepad2 className="w-5 h-5 text-gray-600" />
                                      </div>
                                      <div className="flex-1">
                                        <div className="font-semibold text-gray-800">休闲赛</div>
                                        <div className="text-sm text-gray-600 mt-1">轻松娱乐，不影响排名积分</div>
                                        <div className="text-xs text-gray-500 mt-2 flex items-center gap-1">
                                          <Heart className="w-3 h-3" />
                                          友好环境
                                        </div>
                                      </div>
                                      {matchSettings.mode === 'casual' && (
                                        <motion.div
                                          initial={{ scale: 0 }}
                                          animate={{ scale: 1 }}
                                          className="w-5 h-5 bg-gray-600 rounded-full flex items-center justify-center"
                                        >
                                          <Check className="w-3 h-3 text-white" />
                                        </motion.div>
                                      )}
                                    </div>
                                  </motion.div>
                                </CardContent>
                              </Card>
                            </motion.div>

                            {/* Difficulty Preference */}
                            <motion.div
                              initial={{ opacity: 0, y: 20 }}
                              animate={{ opacity: 1, y: 0 }}
                              transition={{ duration: 0.3, delay: 0.1 }}
                            >
                              <Card className="h-full bg-white/80 backdrop-blur-sm border border-slate-200 shadow-sm hover:shadow-md transition-all duration-300">
                                <CardHeader className="pb-3">
                                  <CardTitle className="flex items-center gap-3 text-gray-700">
                                    <div className="w-8 h-8 bg-gradient-to-br from-gray-100 to-gray-200 rounded-lg flex items-center justify-center">
                                      <Target className="w-4 h-4 text-gray-600" />
                                    </div>
                                    难度偏好
                                  </CardTitle>
                                  <CardDescription className="text-gray-500">
                                    匹配合适的挑战等级
                                  </CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-3">
                                  {[
                                    { 
                                      id: 'easy', 
                                      icon: Shield, 
                                      name: '简单', 
                                      desc: '适合新手，题目相对容易',
                                      color: 'from-gray-200 to-gray-300',
                                      iconColor: 'text-gray-600',
                                      tag: '新手推荐'
                                    },
                                    { 
                                      id: 'medium', 
                                      icon: Target, 
                                      name: '中等', 
                                      desc: '平衡挑战，适合大多数玩家',
                                      color: 'from-gray-200 to-gray-300',
                                      iconColor: 'text-gray-600',
                                      tag: '热门选择'
                                    },
                                    { 
                                      id: 'hard', 
                                      icon: Flame, 
                                      name: '困难', 
                                      desc: '高难度挑战，考验真实水平',
                                      color: 'from-gray-200 to-gray-300',
                                      iconColor: 'text-gray-600',
                                      tag: '高手对决'
                                    },
                                    { 
                                      id: 'mixed', 
                                      icon: Sparkles, 
                                      name: '混合', 
                                      desc: '随机难度，保持新鲜感',
                                      color: 'from-gray-200 to-gray-300',
                                      iconColor: 'text-gray-600',
                                      tag: '趣味无穷'
                                    }
                                  ].map((difficulty) => (
                                    <motion.div
                                      key={difficulty.id}
                                      whileHover={{ scale: 1.02 }}
                                      whileTap={{ scale: 0.98 }}
                                      className={`p-3 border rounded-xl cursor-pointer transition-all duration-200 ${
                                        matchSettings.difficulty === difficulty.id
                                          ? 'border-gray-400 bg-gray-50 shadow-sm'
                                          : 'border-gray-200 hover:border-gray-300 hover:bg-gray-25'
                                      }`}
                                      onClick={() => setMatchSettings(prev => ({ ...prev, difficulty: difficulty.id as any }))}
                                    >
                                      <div className="flex items-center gap-3">
                                        <div className={`w-8 h-8 bg-gradient-to-br ${difficulty.color} rounded-lg flex items-center justify-center flex-shrink-0`}>
                                          <difficulty.icon className={`w-4 h-4 ${difficulty.iconColor}`} />
                                        </div>
                                        <div className="flex-1">
                                          <div className="flex items-center gap-2">
                                            <span className="font-semibold text-gray-800">{difficulty.name}</span>
                                            <span className="text-xs px-2 py-0.5 bg-gray-100 text-gray-600 rounded-full">
                                              {difficulty.tag}
                                            </span>
                                          </div>
                                          <div className="text-xs text-gray-600 mt-0.5">{difficulty.desc}</div>
                                        </div>
                                        {matchSettings.difficulty === difficulty.id && (
                                          <motion.div
                                            initial={{ scale: 0 }}
                                            animate={{ scale: 1 }}
                                            className="w-5 h-5 bg-gray-600 rounded-full flex items-center justify-center"
                                          >
                                            <Check className="w-3 h-3 text-white" />
                                          </motion.div>
                                        )}
                                      </div>
                                    </motion.div>
                                  ))}
                                </CardContent>
                              </Card>
                            </motion.div>

                            {/* Advanced Settings */}
                            <motion.div
                              initial={{ opacity: 0, y: 20 }}
                              animate={{ opacity: 1, y: 0 }}
                              transition={{ duration: 0.3, delay: 0.2 }}
                            >
                              <Card className="h-full bg-white/80 backdrop-blur-sm border border-slate-200 shadow-sm hover:shadow-md transition-all duration-300">
                                <CardHeader className="pb-3">
                                  <CardTitle className="flex items-center gap-3 text-gray-700">
                                    <div className="w-8 h-8 bg-gradient-to-br from-gray-100 to-gray-200 rounded-lg flex items-center justify-center">
                                      <Settings className="w-4 h-4 text-gray-600" />
                                    </div>
                                    高级设置
                                  </CardTitle>
                                  <CardDescription className="text-gray-500">
                                    优化匹配体验
                                  </CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                  {/* Server Region */}
                                  <div>
                                    <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-3">
                                      <Globe className="w-4 h-4 text-gray-500" />
                                      服务器地区
                                    </label>
                                    <div className="space-y-2">
                                      {[
                                        { id: 'auto', name: '自动选择', desc: '推荐', icon: Wifi },
                                        { id: 'asia', name: '亚洲', desc: '低延迟', icon: Globe },
                                        { id: 'america', name: '美洲', desc: '稳定连接', icon: Globe },
                                        { id: 'europe', name: '欧洲', desc: '高速网络', icon: Globe }
                                      ].map((region) => (
                                        <motion.div
                                          key={region.id}
                                          whileHover={{ scale: 1.01 }}
                                          whileTap={{ scale: 0.99 }}
                                          className={`p-2 border rounded-lg cursor-pointer transition-all duration-200 ${
                                            matchSettings.region === region.id
                                              ? 'border-gray-400 bg-gray-50'
                                              : 'border-gray-200 hover:border-gray-300'
                                          }`}
                                          onClick={() => setMatchSettings(prev => ({ ...prev, region: region.id as any }))}
                                        >
                                          <div className="flex items-center gap-2">
                                            <region.icon className="w-4 h-4 text-gray-500" />
                                            <span className="text-sm font-medium text-gray-700">{region.name}</span>
                                            <span className="text-xs text-gray-500 ml-auto">{region.desc}</span>
                                            {matchSettings.region === region.id && (
                                              <Check className="w-4 h-4 text-gray-600 ml-1" />
                                            )}
                                          </div>
                                        </motion.div>
                                      ))}
                                    </div>
                                  </div>

                                  {/* Max Wait Time */}
                                  <div>
                                    <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-3">
                                      <Clock className="w-4 h-4 text-gray-500" />
                                      最大等待时间
                                    </label>
                                    <div className="space-y-2">
                                      {[
                                        { id: 30, name: '30秒', desc: '快速匹配' },
                                        { id: 60, name: '60秒', desc: '推荐' },
                                        { id: 120, name: '2分钟', desc: '精确匹配' },
                                        { id: 300, name: '不限制', desc: '等到匹配' }
                                      ].map((time) => (
                                        <motion.div
                                          key={time.id}
                                          whileHover={{ scale: 1.01 }}
                                          whileTap={{ scale: 0.99 }}
                                          className={`p-2 border rounded-lg cursor-pointer transition-all duration-200 ${
                                            matchSettings.maxWaitTime === time.id
                                              ? 'border-gray-400 bg-gray-50'
                                              : 'border-gray-200 hover:border-gray-300'
                                          }`}
                                          onClick={() => setMatchSettings(prev => ({ ...prev, maxWaitTime: time.id }))}
                                        >
                                          <div className="flex items-center gap-2">
                                            <Timer className="w-4 h-4 text-gray-500" />
                                            <span className="text-sm font-medium text-gray-700">{time.name}</span>
                                            <span className="text-xs text-gray-500 ml-auto">{time.desc}</span>
                                            {matchSettings.maxWaitTime === time.id && (
                                              <Check className="w-4 h-4 text-gray-600 ml-1" />
                                            )}
                                          </div>
                                        </motion.div>
                                      ))}
                                    </div>
                                  </div>
                                </CardContent>
                              </Card>
                            </motion.div>
                          </div>

                          {/* Start Matching Button */}
                          <div className="text-center">
                            <motion.div
                              whileHover={{ scale: 1.05 }}
                              whileTap={{ scale: 0.95 }}
                            >
                              <Button
                                onClick={() => setIsSearching(true)}
                                size="lg"
                                className="bg-gradient-to-r from-gray-600 to-gray-700 hover:from-gray-700 hover:to-gray-800 text-white px-8 py-4 h-auto shadow-lg hover:shadow-xl transition-all duration-300"
                              >
                                <Search className="w-5 h-5 mr-2" />
                                开始匹配
                              </Button>
                            </motion.div>
                          </div>
                        </div>
                      ) : isSearching ? (
                        <Card className="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg">
                          <CardContent className="p-6 text-center">
                            <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                              <motion.div
                                animate={{ rotate: 360 }}
                                transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
                              >
                                <Search className="w-8 h-8 text-blue-600" />
                              </motion.div>
                            </div>
                            <h3 className="text-xl font-bold mb-2">正在寻找对手...</h3>
                            <p className="text-slate-600 mb-4">预计等待时间：30-60秒</p>
                            
                            <div className="flex items-center justify-center gap-2 mb-6">
                              <Clock className="w-4 h-4 text-blue-600" />
                              <span className="text-blue-600 font-mono">{Math.floor(searchTime / 60)}:{(searchTime % 60).toString().padStart(2, '0')}</span>
                            </div>

                            <div className="space-y-3 mb-6">
                              <div className="w-full bg-slate-200 rounded-full h-2">
                                <motion.div 
                                  className="bg-blue-600 h-2 rounded-full"
                                  initial={{ width: '0%' }}
                                  animate={{ width: `${Math.min(100, (searchTime / 60) * 100)}%` }}
                                />
                              </div>
                              <p className="text-xs text-slate-500">匹配系统正在为您寻找合适的对手</p>
                            </div>

                            <Button 
                              variant="outline" 
                              onClick={() => {
                                setIsSearching(false);
                                setSearchTime(0);
                              }}
                            >
                              取消匹配
                            </Button>
                          </CardContent>
                        </Card>
                      ) : (
                        <Card className="bg-gradient-to-r from-yellow-50 to-orange-50 border-yellow-200">
                          <CardContent className="p-6 text-center">
                            <div className="text-4xl mb-4">🎉</div>
                            <h3 className="text-xl font-bold mb-2">找到对手！</h3>
                            <p className="text-slate-600 mb-6">准备开始对战</p>
                            
                            <div className="flex items-center justify-center gap-8 mb-6">
                              <div className="text-center">
                                <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-2">
                                  <span className="text-xl">🦅</span>
                                </div>
                                <p className="font-semibold">你</p>
                                <p className="text-sm text-slate-500">等级 42</p>
                              </div>
                              
                              <div className="text-2xl font-bold text-slate-400">VS</div>
                              
                              <div className="text-center">
                                <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-2">
                                  <span className="text-xl">⚡</span>
                                </div>
                                <p className="font-semibold">AI克星</p>
                                <p className="text-sm text-slate-500">等级 42</p>
                              </div>
                            </div>

                            <Button 
                              size="lg" 
                              className="bg-gradient-to-r from-green-600 to-emerald-600"
                              onClick={() => {
                                setPvpMode('battle');
                                setOpponent(mockOnlinePlayers[1]);
                                setPhase('battle');
                                setBattleMode('solo');
                              }}
                            >
                              <Play className="w-5 h-5 mr-2" />
                              开始对战
                            </Button>
                          </CardContent>
                        </Card>
                      )}
                    </div>
                  )}

                  {/* 房间对战模式 */}
                  {pvpMode === 'rooms' && (
                    <div className="space-y-6">
                      <div className="flex items-center justify-between">
                        <h3 className="text-lg font-semibold">对战房间</h3>
                        <Button 
                          onClick={() => setShowCreateRoom(true)}
                          className="bg-gradient-to-r from-blue-600 to-purple-600"
                        >
                          <Plus className="w-4 h-4 mr-2" />
                          创建房间
                        </Button>
                      </div>

                      <div className="grid gap-4">
                        {mockBattleRooms.map((room) => (
                          <Card key={room.id} className="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg">
                            <CardContent className="p-4">
                              <div className="flex items-center justify-between">
                                <div className="flex items-center gap-4">
                                  <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-500 rounded-lg flex items-center justify-center">
                                    {room.isPrivate ? <Lock className="w-6 h-6 text-white" /> : <Globe className="w-6 h-6 text-white" />}
                                  </div>
                                  <div>
                                    <div className="flex items-center gap-2 mb-1">
                                      <h4 className="font-semibold">{room.name}</h4>
                                      <Badge variant={room.mode === 'ranked' ? 'default' : 'secondary'} className="text-xs">
                                        {room.mode === 'ranked' ? '排位' : room.mode === 'casual' ? '休闲' : '私人'}
                                      </Badge>
                                      <Badge variant={room.status === 'waiting' ? 'outline' : room.status === 'in-progress' ? 'default' : 'secondary'} className="text-xs">
                                        {room.status === 'waiting' ? '等待中' : room.status === 'in-progress' ? '进行中' : '已结束'}
                                      </Badge>
                                    </div>
                                    <div className="flex items-center gap-4 text-sm text-slate-500">
                                      <span className="flex items-center gap-1">
                                        <Users className="w-3 h-3" />
                                        {room.currentPlayers}/{room.maxPlayers}
                                      </span>
                                      <span className="flex items-center gap-1">
                                        <Eye className="w-3 h-3" />
                                        {room.spectators.length}
                                      </span>
                                      <span className="flex items-center gap-1">
                                        <Timer className="w-3 h-3" />
                                        {room.settings.timePerRound}s/题
                                      </span>
                                      <span className="flex items-center gap-1">
                                        <Target className="w-3 h-3" />
                                        {room.settings.difficulty === 'easy' ? '简单' : room.settings.difficulty === 'medium' ? '中等' : room.settings.difficulty === 'hard' ? '困难' : '混合'}
                                      </span>
                                    </div>
                                  </div>
                                </div>
                                <div className="flex items-center gap-2">
                                  {room.status === 'waiting' && room.currentPlayers < room.maxPlayers && (
                                    <Button size="sm" className="bg-green-600 hover:bg-green-700">
                                      <Play className="w-3 h-3 mr-1" />
                                      加入
                                    </Button>
                                  )}
                                  {room.status === 'in-progress' && room.settings.allowSpectators && (
                                    <Button size="sm" variant="outline">
                                      <Eye className="w-3 h-3 mr-1" />
                                      观战
                                    </Button>
                                  )}
                                  <Button size="sm" variant="ghost">
                                    <MoreHorizontal className="w-3 h-3" />
                                  </Button>
                                </div>
                              </div>
                              
                              {room.players.length > 0 && (
                                <div className="mt-3 pt-3 border-t border-slate-200">
                                  <div className="flex items-center gap-2">
                                    <span className="text-xs text-slate-500">玩家：</span>
                                    {room.players.map((player, index) => (
                                      <div key={player.id} className="flex items-center gap-1">
                                        <span className="text-lg">{player.avatar}</span>
                                        <span className="text-sm font-medium">{player.name}</span>
                                        {player.badge && <span className="text-xs">{player.badge}</span>}
                                        {index < room.players.length - 1 && <span className="text-slate-300 mx-1">|</span>}
                                      </div>
                                    ))}
                                  </div>
                                </div>
                              )}
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 好友对战模式 */}
                  {pvpMode === 'friends' && (
                    <div className="space-y-6">
                      <div className="flex items-center justify-between">
                        <h3 className="text-lg font-semibold">好友列表</h3>
                        <Button variant="outline">
                          <UserPlus className="w-4 h-4 mr-2" />
                          添加好友
                        </Button>
                      </div>

                      <div className="grid gap-4">
                        {mockFriends.map((friend) => (
                          <Card key={friend.id} className="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg">
                            <CardContent className="p-4">
                              <div className="flex items-center justify-between">
                                <div className="flex items-center gap-4">
                                  <div className="relative">
                                    <div className="w-12 h-12 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
                                      <span className="text-2xl">{friend.avatar}</span>
                                    </div>
                                    {friend.isOnline ? (
                                      <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-green-500 rounded-full border-2 border-white flex items-center justify-center">
                                        <Wifi className="w-2 h-2 text-white" />
                                      </div>
                                    ) : (
                                      <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-slate-400 rounded-full border-2 border-white flex items-center justify-center">
                                        <WifiOff className="w-2 h-2 text-white" />
                                      </div>
                                    )}
                                  </div>
                                  <div>
                                    <div className="flex items-center gap-2 mb-1">
                                      <h4 className="font-semibold">{friend.name}</h4>
                                      <Badge variant="outline" className="text-xs">
                                        Lv.{friend.level}
                                      </Badge>
                                      {friend.mutualFriends && (
                                        <Badge variant="secondary" className="text-xs">
                                          {friend.mutualFriends}个共同好友
                                        </Badge>
                                      )}
                                    </div>
                                    <div className="flex items-center gap-2 text-sm">
                                      <span className={friend.isOnline ? 'text-green-600' : 'text-slate-500'}>
                                        {friend.status}
                                      </span>
                                      {!friend.isOnline && friend.lastSeen && (
                                        <span className="text-slate-400 text-xs">
                                          最后在线：{friend.lastSeen.toLocaleDateString()}
                                        </span>
                                      )}
                                    </div>
                                  </div>
                                </div>
                                <div className="flex items-center gap-2">
                                  {friend.isOnline ? (
                                    <>
                                      <Button size="sm" className="bg-green-600 hover:bg-green-700">
                                        <Swords className="w-3 h-3 mr-1" />
                                        邀请对战
                                      </Button>
                                      <Button size="sm" variant="outline">
                                        <MessageCircle className="w-3 h-3 mr-1" />
                                        聊天
                                      </Button>
                                    </>
                                  ) : (
                                    <Button size="sm" variant="outline" disabled>
                                      <MessageCircle className="w-3 h-3 mr-1" />
                                      发送消息
                                    </Button>
                                  )}
                                  <Button size="sm" variant="ghost">
                                    <MoreHorizontal className="w-3 h-3" />
                                  </Button>
                                </div>
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              </TabsContent>

              {/* Leaderboard Tab */}
              <TabsContent value="leaderboard" className="space-y-6">
                <div className="grid lg:grid-cols-3 gap-6">
                  {/* 当前赛季信息 */}
                  <Card className="bg-gradient-to-br from-yellow-50 to-orange-50 border-yellow-200">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <Calendar className="w-5 h-5 text-yellow-600" />
                        当前赛季
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3">
                        <div>
                          <h3 className="font-semibold text-lg">赛季一：觉醒</h3>
                          <p className="text-sm text-slate-600">2024年8月 - 2024年11月</p>
                        </div>
                        <div className="space-y-2">
                          <div className="flex justify-between text-sm">
                            <span>赛季进度</span>
                            <span>75%</span>
                          </div>
                          <Progress value={75} className="h-2" />
                        </div>
                        <div className="pt-2">
                          <h4 className="font-medium mb-2">赛季奖励</h4>
                          <div className="space-y-1 text-sm">
                            <div className="flex items-center gap-2">
                              <Crown className="w-4 h-4 text-yellow-500" />
                              <span>王者：专属头衔 + 500积分</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <Star className="w-4 h-4 text-blue-500" />
                              <span>大师：专属徽章 + 300积分</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <Medal className="w-4 h-4 text-purple-500" />
                              <span>钻石：纪念徽章 + 200积分</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* 你的排名 */}
                  <Card className="bg-gradient-to-br from-blue-50 to-indigo-50 border-blue-200">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <TrendingUp className="w-5 h-5 text-blue-600" />
                        你的排名
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-4">
                        <div className="text-center">
                          <div className="text-3xl font-bold text-blue-600">#42</div>
                          <p className="text-sm text-slate-600">当前排名</p>
                        </div>
                        <div className="space-y-2">
                          <div className="flex justify-between text-sm">
                            <span>积分</span>
                            <span className="font-medium">1,850</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span>胜率</span>
                            <span className="font-medium text-green-600">68%</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span>连胜</span>
                            <span className="font-medium text-orange-600">5</span>
                          </div>
                        </div>
                        <div className="pt-2">
                          <Badge variant="outline" className="w-full justify-center bg-blue-100 text-blue-700 border-blue-300">
                            🏅 铂金勇士
                          </Badge>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* 最近战绩 */}
                  <Card className="bg-gradient-to-br from-green-50 to-emerald-50 border-green-200">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <Gamepad2 className="w-5 h-5 text-green-600" />
                        最近战绩
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3">
                        {[
                          { result: 'W', opponent: '策略大师', score: '85-72' },
                          { result: 'W', opponent: 'R.O.O.K.I.E', score: '92-68' },
                          { result: 'L', opponent: '终极智脑', score: '76-89' },
                          { result: 'W', opponent: '闪电侠', score: '81-79' },
                          { result: 'W', opponent: '策略大师', score: '88-74' }
                        ].map((match, index) => (
                          <div key={index} className="flex items-center justify-between text-sm">
                            <div className="flex items-center gap-2">
                              <Badge 
                                variant={match.result === 'W' ? 'default' : 'destructive'}
                                className="w-6 h-6 p-0 flex items-center justify-center"
                              >
                                {match.result}
                              </Badge>
                              <span>{match.opponent}</span>
                            </div>
                            <span className="text-slate-600">{match.score}</span>
                          </div>
                        ))}
                      </div>
                    </CardContent>
                  </Card>
                </div>

                {/* 排行榜 */}
                <Card className="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Trophy className="w-5 h-5 text-yellow-600" />
                      全球排行榜
                    </CardTitle>
                    <CardDescription>
                      当前赛季顶级玩家排名
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {mockLeaderboard.map((player, index) => (
                        <motion.div
                          key={player.playerId}
                          initial={{ opacity: 0, x: -20 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: index * 0.1 }}
                          className={`flex items-center gap-4 p-4 rounded-lg transition-all duration-200 ${
                            index < 3 ? 'bg-gradient-to-r from-yellow-50 to-orange-50 border border-yellow-200' : 'bg-slate-50'
                          }`}
                        >
                          <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm ${
                            index === 0 ? 'bg-yellow-500 text-white' :
                            index === 1 ? 'bg-gray-400 text-white' :
                            index === 2 ? 'bg-amber-600 text-white' :
                            'bg-slate-300 text-slate-700'
                          }`}>
                            {player.rank}
                          </div>
                          
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-1">
                              <h3 className="font-semibold">{player.playerName}</h3>
                              {player.badge && <span className="text-lg">{player.badge}</span>}
                              {player.title && (
                                <Badge variant="outline" className="text-xs">
                                  {player.title}
                                </Badge>
                              )}
                            </div>
                            <div className="flex items-center gap-4 text-sm text-slate-600">
                              <span>积分: {player.rankPoints}</span>
                              <span>胜率: {player.winRate}%</span>
                              <span>连胜: {player.currentStreak}</span>
                            </div>
                          </div>
                          
                          <div className="text-right">
                            <div className="font-semibold text-lg">{player.wins}-{player.losses}-{player.draws}</div>
                            <div className="text-sm text-slate-500">胜-负-平</div>
                          </div>
                        </motion.div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </motion.div>
        </div>
      </div>
    );
  }

  if (phase === 'battle') {
    let currentStats, timeRemaining, totalRounds;
    
    if (pvpMode === 'battle') {
      currentStats = pvpBattleStats;
      timeRemaining = pvpBattleStats.timeRemaining;
      totalRounds = pvpBattleStats.totalRounds;
    } else if (battleMode === 'team') {
      currentStats = teamBattleStats;
      timeRemaining = teamBattleStats.timeRemaining;
      totalRounds = teamBattleStats.totalRounds;
    } else {
      currentStats = battleStats;
      timeRemaining = battleStats.timeRemaining;
      totalRounds = battleStats.totalRounds;
    }
    
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-indigo-50">
        <div className="container mx-auto px-4 py-8">
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.5 }}
          >
            {/* 对战页面顶部返回区域 */}
            <div className="flex items-center justify-between mb-6">
              <motion.div
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <Button 
                  variant="ghost" 
                  onClick={onBack}
                  className="flex items-center gap-2 text-slate-600 hover:text-slate-800 hover:bg-slate-100 transition-all duration-200"
                >
                  <ArrowLeft className="w-4 h-4" />
                  返回对战大厅
                </Button>
              </motion.div>
              
              <div className="flex items-center gap-2">
                <Badge variant="outline" className="px-3 py-1">
                  {pvpMode === 'battle' ? '真人对战' :
                   battleMode === 'team' ? '团队模式' : '单人对战'}
                </Badge>
                <Badge variant="outline" className="px-3 py-1 bg-blue-50 text-blue-600 border-blue-200">
                  第 {currentStats.round} / {totalRounds} 轮
                </Badge>
              </div>
            </div>

            {/* 优化后的战斗状态栏 */}
            <div className="grid grid-cols-3 gap-6 mb-8">
              {/* 玩家状态 */}
              <Card className="bg-white/80 backdrop-blur-sm border-blue-200 shadow-lg">
                <CardContent className="p-4">
                  <div className="flex items-center gap-3 mb-3">
                    <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center shadow-md">
                      {pvpMode === 'battle' ? <UserCheck className="w-6 h-6 text-white" /> :
                       battleMode === 'team' ? <Users className="w-6 h-6 text-white" /> : 
                       <Gamepad2 className="w-6 h-6 text-white" />}
                    </div>
                    <div>
                      <h3 className="font-semibold text-blue-700">
                        {pvpMode === 'battle' ? '你' :
                         battleMode === 'team' ? '你的团队' : '玩家'}
                      </h3>
                      <p className="text-sm text-slate-500">
                        {pvpMode === 'battle' ? '🦅 等级42' :
                         battleMode === 'team' ? `${selectedTeamSize}人团队` : '你'}
                      </p>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>分数</span>
                      <span className="font-bold text-blue-600">
                        {pvpMode === 'battle' ? (currentStats as PvPBattleStats).player1Score :
                         battleMode === 'team' ? (currentStats as TeamBattleStats).playerTeamScore : 
                         (currentStats as BattleStats).playerScore}
                      </span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>正确</span>
                      <span className="font-medium">
                        {pvpMode === 'battle' ? (currentStats as PvPBattleStats).player1Correct :
                         battleMode === 'team' ? (currentStats as TeamBattleStats).playerTeamCorrect : 
                         (currentStats as BattleStats).playerCorrect}/{currentStats.round - 1}
                      </span>
                    </div>
                    <Progress 
                      value={pvpMode === 'battle' ? ((currentStats as PvPBattleStats).player1Correct / totalRounds * 100) :
                             battleMode === 'team' ? ((currentStats as TeamBattleStats).playerTeamCorrect / totalRounds * 100) : 
                             ((currentStats as BattleStats).playerCorrect / totalRounds * 100)} 
                      className="h-2 bg-blue-100" 
                    />
                  </div>
                </CardContent>
              </Card>

              {/* 时间和回合 */}
              <Card className="bg-white/80 backdrop-blur-sm border-slate-200 shadow-lg">
                <CardContent className="p-4 text-center">
                  <div className="mb-3">
                    <motion.div
                      animate={{ scale: timeRemaining <= 5 ? [1, 1.1, 1] : 1 }}
                      transition={{ duration: 0.5, repeat: timeRemaining <= 5 ? Infinity : 0 }}
                    >
                      <Timer className={`w-8 h-8 mx-auto mb-2 ${timeRemaining <= 5 ? 'text-red-500' : 'text-yellow-500'}`} />
                    </motion.div>
                    <div className={`text-2xl font-bold ${timeRemaining <= 5 ? 'text-red-600' : 'text-slate-700'}`}>
                      {timeRemaining}
                    </div>
                    <p className="text-sm text-slate-500">秒</p>
                  </div>
                  <div className="text-sm">
                    第 {currentStats.round} / {totalRounds} 回合
                  </div>
                  <Progress value={(currentStats.round - 1) / totalRounds * 100} className="h-2 mt-2" />
                </CardContent>
              </Card>

              {/* 对手状态 */}
              <Card className="bg-white/80 backdrop-blur-sm border-red-200 shadow-lg">
                <CardContent className="p-4">
                  <div className="flex items-center gap-3 mb-3">
                    <div className="relative text-2xl">
                      {pvpMode === 'battle' ? opponent?.avatar : selectedAI?.emoji}
                      {/* AI状态指示器 */}
                      {pvpMode !== 'battle' && (
                        <div className="absolute -bottom-1 -right-1">
                          {aiStatus === 'thinking' && (
                            <motion.div
                              animate={{ scale: [1, 1.2, 1] }}
                              transition={{ duration: 1, repeat: Infinity }}
                              className="w-4 h-4 bg-blue-500 rounded-full border-2 border-white flex items-center justify-center"
                            >
                              <motion.div
                                animate={{ rotate: 360 }}
                                transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
                                className="w-2 h-2 border border-white border-t-transparent rounded-full"
                              />
                            </motion.div>
                          )}
                          {aiStatus === 'answering' && (
                            <div className="w-4 h-4 bg-orange-500 rounded-full border-2 border-white flex items-center justify-center">
                              <Zap className="w-2 h-2 text-white" />
                            </div>
                          )}
                          {aiStatus === 'completed' && (
                            <div className="w-4 h-4 bg-green-500 rounded-full border-2 border-white flex items-center justify-center">
                              <Check className="w-2 h-2 text-white" />
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                    <div className="flex-1">
                      <h3 className="font-semibold text-red-700">
                        {pvpMode === 'battle' ? opponent?.name :
                         battleMode === 'team' ? `${selectedAI?.name}团队` : selectedAI?.name}
                      </h3>
                      <div className="flex items-center gap-2">
                        <p className="text-sm text-slate-500">
                          {pvpMode === 'battle' ? `等级 ${opponent?.level}` :
                           battleMode === 'team' ? `AI ${selectedTeamSize}人团队` : 'AI对手'}
                        </p>
                        {/* AI状态文本 */}
                        {pvpMode !== 'battle' && (
                          <motion.span 
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            className="text-xs px-2 py-0.5 rounded-full font-medium"
                            style={{
                              backgroundColor: 
                                aiStatus === 'thinking' ? '#3b82f6' :
                                aiStatus === 'answering' ? '#f59e0b' :
                                aiStatus === 'completed' ? '#10b981' : '#6b7280',
                              color: 'white'
                            }}
                          >
                            {aiStatus === 'thinking' && '思考中'}
                            {aiStatus === 'answering' && '答题中'}
                            {aiStatus === 'completed' && '已完成'}
                            {aiStatus === 'waiting' && '等待中'}
                          </motion.span>
                        )}
                      </div>
                    </div>
                  </div>
                  
                  {/* AI状态信息区域 - 固定高度避免布局抖动 */}
                  {pvpMode !== 'battle' && (
                    <div className="mb-3 h-16 flex flex-col justify-center">
                      {/* AI思考进度条 */}
                      {aiStatus === 'thinking' && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: 'auto' }}
                          exit={{ opacity: 0, height: 0 }}
                          transition={{ duration: 0.2 }}
                        >
                          <div className="flex justify-between text-xs text-slate-500 mb-1">
                            <span>AI思考进度</span>
                            <span>{Math.round(aiThinkingProgress)}%</span>
                          </div>
                          <div className="w-full bg-slate-200 rounded-full h-2">
                            <motion.div 
                              className="bg-gradient-to-r from-blue-500 to-blue-600 h-2 rounded-full"
                              initial={{ width: '0%' }}
                              animate={{ width: `${aiThinkingProgress}%` }}
                              transition={{ duration: 0.1 }}
                            />
                          </div>
                        </motion.div>
                      )}
                      
                      {/* AI答题时间显示 */}
                      {aiAnswerTime && aiStatus === 'completed' && (
                        <motion.div
                          initial={{ opacity: 0, scale: 0.9 }}
                          animate={{ opacity: 1, scale: 1 }}
                          transition={{ duration: 0.3 }}
                          className="p-2 bg-green-50 rounded-lg border border-green-200"
                        >
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-green-700 font-medium">AI答题用时</span>
                            <span className="text-green-600 font-mono">{aiAnswerTime.toFixed(2)}秒</span>
                          </div>
                        </motion.div>
                      )}
                      
                      {/* 等待和答题状态的占位区域 */}
                      {(aiStatus === 'waiting' || aiStatus === 'answering') && (
                        <div className="flex items-center justify-center h-full">
                          <div className="text-xs text-slate-400 text-center">
                            {aiStatus === 'waiting' && '等待开始...'}
                            {aiStatus === 'answering' && '正在答题...'}
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                  
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>分数</span>
                      <span className="font-bold text-red-600">
                        {pvpMode === 'battle' ? (currentStats as PvPBattleStats).player2Score :
                         battleMode === 'team' ? (currentStats as TeamBattleStats).aiTeamScore : 
                         (currentStats as BattleStats).aiScore}
                      </span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>正确</span>
                      <span className="font-medium">
                        {pvpMode === 'battle' ? (currentStats as PvPBattleStats).player2Correct :
                         battleMode === 'team' ? (currentStats as TeamBattleStats).aiTeamCorrect : 
                         (currentStats as BattleStats).aiCorrect}/{currentStats.round - 1}
                      </span>
                    </div>
                    <Progress 
                      value={pvpMode === 'battle' ? ((currentStats as PvPBattleStats).player2Correct / totalRounds * 100) :
                             battleMode === 'team' ? ((currentStats as TeamBattleStats).aiTeamCorrect / totalRounds * 100) : 
                             ((currentStats as BattleStats).aiCorrect / totalRounds * 100)} 
                      className="h-2 bg-red-100" 
                    />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 优化后的挑战区域 */}
            {currentChallenge && (
              <Card className="bg-white/90 backdrop-blur-sm border-slate-200 shadow-xl mb-6">
                <CardContent className="p-8">
                  <div className="text-center space-y-6">
                    <div className="flex items-center justify-center gap-3 mb-4">
                      <Badge variant="outline" className="px-3 py-1">
                        {pvpMode === 'battle' ? '真人对战' :
                         battleMode === 'team' ? '团队挑战' : '单人挑战'}
                      </Badge>
                      <Badge variant="outline" className="px-3 py-1 bg-slate-100 text-slate-600">
                        {currentChallenge.category}
                      </Badge>
                      <Badge variant="outline" className={`px-3 py-1 ${
                        currentChallenge.difficulty === 'easy' ? 'bg-green-50 text-green-600 border-green-200' :
                        currentChallenge.difficulty === 'medium' ? 'bg-yellow-50 text-yellow-600 border-yellow-200' :
                        'bg-red-50 text-red-600 border-red-200'
                      }`}>
                        {currentChallenge.difficulty === 'easy' ? '简单' :
                         currentChallenge.difficulty === 'medium' ? '中等' : '困难'}
                      </Badge>
                      {pvpMode === 'battle' && (
                        <Badge variant="outline" className="px-3 py-1 bg-green-50 text-green-600 border-green-200">
                          <Wifi className="w-3 h-3 mr-1" />
                          实时对战
                        </Badge>
                      )}
                    </div>
                    
                    <h2 className="text-2xl font-bold text-slate-800">{currentChallenge.question}</h2>
                    
                    {/* 反应测试 */}
                    {currentChallenge.type === 'reaction' && !currentChallenge.completed && (
                      <div className="space-y-4">
                        {reactionStartTime ? (
                          <motion.div
                            initial={{ scale: 0 }}
                            animate={{ scale: 1 }}
                            className="w-32 h-32 bg-gradient-to-br from-green-400 to-green-500 rounded-full mx-auto cursor-pointer flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-200"
                            onClick={() => handleAnswer('click')}
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                          >
                            <span className="text-2xl font-bold text-white">点击!</span>
                          </motion.div>
                        ) : (
                          <div className="w-32 h-32 bg-gradient-to-br from-slate-400 to-slate-500 rounded-full mx-auto flex items-center justify-center shadow-lg">
                            <span className="text-xl text-white">等待...</span>
                          </div>
                        )}
                      </div>
                    )}

                    {/* 选择题 */}
                    {currentChallenge.options && currentChallenge.type !== 'reaction' && !currentChallenge.completed && (
                      <div className="mt-6">
                        <p className="text-sm text-slate-600 mb-3">选择答案：</p>
                        <div className="grid grid-cols-2 gap-3">
                          {currentChallenge.options.map((option, index) => (
                            <motion.div
                              key={`${currentChallenge.id}-${option}-${index}`}
                              whileHover={{ scale: 1.02 }}
                              whileTap={{ scale: 0.98 }}
                            >
                              <Button
                                variant="outline"
                                size="lg"
                                onClick={() => handleAnswer(option)}
                                className="w-full h-12 text-left justify-start bg-white hover:bg-blue-50 hover:border-blue-300 border-slate-200"
                              >
                                <span className="w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center text-xs mr-3 flex-shrink-0">
                                  {String.fromCharCode(65 + index)}
                                </span>
                                <span className="truncate">{option}</span>
                              </Button>
                            </motion.div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* 数学题输入 */}
                    {currentChallenge.type === 'math' && !currentChallenge.options && !currentChallenge.completed && (
                      <div className="space-y-4">
                        <div className="grid grid-cols-5 gap-3 max-w-md mx-auto">
                          {Array.from({ length: 10 }, (_, i) => (
                            <motion.div
                              key={i}
                              whileHover={{ scale: 1.05 }}
                              whileTap={{ scale: 0.95 }}
                            >
                              <Button
                                variant="outline"
                                size="lg"
                                className="h-12 bg-white hover:bg-blue-50 border-2 hover:border-blue-300"
                                onClick={() => handleAnswer(i)}
                              >
                                {i}
                              </Button>
                            </motion.div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* 答题结果显示 */}
                    {currentChallenge.completed && (
                      <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="grid md:grid-cols-2 gap-6 mt-8"
                      >
                        <div className="text-center">
                          <h3 className="text-lg font-semibold mb-3 flex items-center justify-center gap-2">
                            <span className="text-xl">🦅</span>
                            {pvpMode === 'battle' ? '你的答案' :
                             battleMode === 'team' ? '你的团队' : '你的答案'}
                          </h3>
                          <div className={`text-2xl p-4 rounded-lg shadow-md ${
                            currentChallenge.playerAnswer === currentChallenge.correctAnswer 
                              ? 'bg-green-100 text-green-700 border-2 border-green-300' 
                              : 'bg-red-100 text-red-700 border-2 border-red-300'
                          }`}>
                            {currentChallenge.playerAnswer === 'timeout' ? '超时' : String(currentChallenge.playerAnswer)}
                            {currentChallenge.playerAnswer === currentChallenge.correctAnswer ? (
                              <Check className="w-6 h-6 inline ml-2" />
                            ) : (
                              <X className="w-6 h-6 inline ml-2" />
                            )}
                          </div>
                          {currentChallenge.timeToAnswer && (
                            <p className="text-sm text-slate-500 mt-2">
                              用时: {currentChallenge.timeToAnswer.toFixed(2)}秒
                            </p>
                          )}
                        </div>
                        
                        <div className="text-center">
                          <h3 className="text-lg font-semibold mb-3 flex items-center justify-center gap-2">
                            <span className="text-xl">
                              {pvpMode === 'battle' ? opponent?.avatar : selectedAI?.emoji}
                            </span>
                            {pvpMode === 'battle' ? `${opponent?.name}的答案` :
                             battleMode === 'team' ? 'AI团队答案' : 'AI答案'}
                          </h3>
                          

                          
                          <div className={`text-2xl p-4 rounded-lg shadow-md ${
                            showAIAnswer && currentChallenge.aiAnswer === currentChallenge.correctAnswer 
                              ? 'bg-green-100 text-green-700 border-2 border-green-300' 
                              : showAIAnswer && currentChallenge.aiAnswer !== currentChallenge.correctAnswer
                              ? 'bg-red-100 text-red-700 border-2 border-red-300'
                              : 'bg-gray-100 text-gray-700 border-2 border-gray-300'
                          }`}>
                            {showAIAnswer ? String(currentChallenge.aiAnswer) : 
                             pvpMode === 'battle' ? '答题中...' : (
                               aiStatus === 'thinking' ? '思考中...' :
                               aiStatus === 'answering' ? '答题中...' : '准备中...'
                             )}
                            {showAIAnswer && currentChallenge.aiAnswer !== undefined && (
                              currentChallenge.aiAnswer === currentChallenge.correctAnswer ? (
                                <Check className="w-6 h-6 inline ml-2" />
                              ) : (
                                <X className="w-6 h-6 inline ml-2" />
                              )
                            )}
                          </div>
                          
                          {/* AI答题详情 */}
                          {pvpMode !== 'battle' && showAIAnswer && aiAnswerTime && (
                            <div className="mt-3 space-y-1">
                              <p className="text-sm text-slate-500">
                                AI用时: {aiAnswerTime.toFixed(2)}秒
                              </p>
                              <div className="flex items-center justify-center gap-2 text-xs">
                                <span className="px-2 py-1 bg-slate-100 rounded-full text-slate-600">
                                  {selectedAI?.personality.split('，')[0]}
                                </span>
                                <span className="px-2 py-1 bg-slate-100 rounded-full text-slate-600">
                                  难度: {Math.round((selectedAI?.difficulty || 0.5) * 100)}%
                                </span>
                              </div>
                            </div>
                          )}
                          
                          {pvpMode === 'battle' && showAIAnswer && (
                            <p className="text-sm text-slate-500 mt-2">
                              实时对战结果
                            </p>
                          )}
                        </div>
                      </motion.div>
                    )}
                  </div>
                </CardContent>
              </Card>
            )}
          </motion.div>
        </div>
      </div>
    );
  }

  if (phase === 'result') {
    let currentStats, playerScore, opponentScore, opponentName, opponentAvatar;
    
    if (pvpMode === 'battle') {
      currentStats = pvpBattleStats;
      playerScore = currentStats.player1Score;
      opponentScore = currentStats.player2Score;
      opponentName = opponent?.name || '对手';
      opponentAvatar = opponent?.avatar || '🤖';
    } else if (battleMode === 'team') {
      currentStats = teamBattleStats;
      playerScore = currentStats.playerTeamScore;
      opponentScore = currentStats.aiTeamScore;
      opponentName = `${selectedAI?.name}团队`;
      opponentAvatar = selectedAI?.emoji || '🤖';
    } else {
      currentStats = battleStats;
      playerScore = currentStats.playerScore;
      opponentScore = currentStats.aiScore;
      opponentName = selectedAI?.name || 'AI';
      opponentAvatar = selectedAI?.emoji || '🤖';
    }
    
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
        <div className="container mx-auto px-4 py-8">
          {/* 结果页面顶部返回区域 */}
          <div className="flex items-center justify-between mb-6">
            <motion.div
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
            >
              <Button 
                variant="ghost" 
                onClick={onBack}
                className="flex items-center gap-2 text-slate-600 hover:text-slate-800 hover:bg-slate-100 transition-all duration-200"
              >
                <ArrowLeft className="w-4 h-4" />
                返回对战大厅
              </Button>
            </motion.div>
            
            <div className="flex items-center gap-2">
              <Badge variant="outline" className="px-3 py-1">
                {pvpMode === 'battle' ? '真人对战' :
                 battleMode === 'team' ? '团队模式' : '单人对战'}
              </Badge>
              <Badge 
                variant="outline" 
                className={`px-3 py-1 ${
                  battleResult === 'victory' ? 'bg-green-50 text-green-600 border-green-200' :
                  battleResult === 'defeat' ? 'bg-red-50 text-red-600 border-red-200' :
                  'bg-blue-50 text-blue-600 border-blue-200'
                }`}
              >
                {battleResult === 'victory' ? '胜利' :
                 battleResult === 'defeat' ? '败北' : '平局'}
              </Badge>
            </div>
          </div>

          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.6 }}
            className="text-center"
          >
            <Card className="max-w-2xl mx-auto bg-white/90 backdrop-blur-sm shadow-xl">
              <CardContent className="p-8">
                <motion.div
                  animate={{ scale: [1, 1.1, 1] }}
                  transition={{ duration: 2, repeat: Infinity }}
                  className="text-6xl mb-4"
                >
                  {battleResult === 'victory' ? '🏆' : battleResult === 'defeat' ? '💀' : '🤝'}
                </motion.div>
                
                <h2 className={`text-3xl font-bold mb-4 ${
                  battleResult === 'victory' ? 'text-green-600' :
                  battleResult === 'defeat' ? 'text-red-600' : 'text-blue-600'
                }`}>
                  {battleResult === 'victory' ? 
                    (pvpMode === 'battle' ? '真人对战胜利！' :
                     battleMode === 'team' ? '团队胜利！' : '胜利！') :
                   battleResult === 'defeat' ? 
                    (pvpMode === 'battle' ? '真人对战败北！' :
                     battleMode === 'team' ? '团队败北！' : '败北！') : 
                    (pvpMode === 'battle' ? '真人对战平局！' :
                     battleMode === 'team' ? '团队平局！' : '平局！')}
                </h2>

                <div className="grid grid-cols-2 gap-6 mb-6">
                  <div className="text-center">
                    <div className="flex items-center justify-center gap-2 mb-2">
                      <span className="text-2xl">🦅</span>
                      <h3 className="font-semibold">
                        {pvpMode === 'battle' ? '你' :
                         battleMode === 'team' ? '你的团队' : '你的表现'}
                      </h3>
                    </div>
                    <div className="text-2xl font-bold text-blue-600">
                      {playerScore} 分
                    </div>
                    <div className="text-sm text-slate-500">
                      {pvpMode === 'battle' ? (currentStats as PvPBattleStats).player1Correct :
                       battleMode === 'team' ? (currentStats as TeamBattleStats).playerTeamCorrect : 
                       (currentStats as BattleStats).playerCorrect}/
                      {currentStats.totalRounds} 正确
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="flex items-center justify-center gap-2 mb-2">
                      <span className="text-2xl">{opponentAvatar}</span>
                      <h3 className="font-semibold">{opponentName}</h3>
                    </div>
                    <div className="text-2xl font-bold text-red-600">
                      {opponentScore} 分
                    </div>
                    <div className="text-sm text-slate-500">
                      {pvpMode === 'battle' ? (currentStats as PvPBattleStats).player2Correct :
                       battleMode === 'team' ? (currentStats as TeamBattleStats).aiTeamCorrect : 
                       (currentStats as BattleStats).aiCorrect}/
                      {currentStats.totalRounds} 正确
                    </div>
                  </div>
                </div>

                {battleResult === 'victory' && (
                  <div className="mb-6 p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                    <h4 className="font-semibold text-yellow-800 mb-2">奖励获得！</h4>
                    <div className="flex justify-center gap-4 text-sm">
                      <div className="flex items-center gap-1">
                        <Star className="w-4 h-4 text-yellow-600" />
                        <span>+{pvpMode === 'battle' ? '80' : '50'} 排位积分</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <Trophy className="w-4 h-4 text-yellow-600" />
                        <span>+{pvpMode === 'battle' ? '30' : battleMode === 'team' ? '25' : '15'} 经验值</span>
                      </div>
                      {pvpMode === 'battle' && (
                        <div className="flex items-center gap-1">
                          <Crown className="w-4 h-4 text-yellow-600" />
                          <span>真人对战成就</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                <div className="space-y-4">
                  <Button 
                    onClick={() => finalTestResult && onComplete(finalTestResult)}
                    className="w-full bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700"
                    disabled={!finalTestResult}
                  >
                    <Trophy className="w-4 h-4 mr-2" />
                    查看数据分析
                  </Button>
                  <div className="grid grid-cols-2 gap-3">
                    <Button 
                      onClick={resetBattle}
                      className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700"
                    >
                      <RotateCcw className="w-4 h-4 mr-2" />
                      再次挑战
                    </Button>
                    <Button 
                      onClick={onBack}
                      variant="outline"
                      className="border-slate-300 hover:bg-slate-50"
                    >
                      <ArrowLeft className="w-4 h-4 mr-2" />
                      返回大厅
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </motion.div>
        </div>
      </div>
    );
  }

  return null;
}